16,554
社区成员
'给定数组arr,arr中所有的值都为正整数且不重复。每个值代表一种面值的货币,
'每种面值的货币可以使用任意张,再给定一个aim,代表要找的钱数,求组成aim的最少货币数。
'如果无解,请返回-1. 数据范围:数组大小满足 0 <= n <=10000 ,
'数组中每个数字都满足 0 < val <=10000,0 <= aim <=100000
'要求:时间复杂度 O(n×aim) ,空间复杂度 O(aim)。
'[5,2,3],20 结果为4
我的方法:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = InputBox("输入数组及要找的钱数(大于零小于10000)" + vbCrLf + "例如:[5,2,3],20", "输入")
Dim arrSi As Integer = 0, arrEi As Integer = 0, aim As Integer = 0, myarr() As Integer, mynum As Integer = 0
Dim arrstr As String = String.Empty, s As String = String.Empty, cf As Boolean = False
If str <> String.Empty Then '输入不为空’
Dim strL As Integer = Len(Str)
If strL >= 5 Then '输入长度>=5’
Dim zn As Integer = 0, yn As Integer = 0
For i As Integer = 1 To strL - 1 '字符“[”出现次数及位置
If str.Substring(i - 1, 1) = "[" Then
zn += 1
arrSi = i - 1
End If
If str.Substring(i - 1, 1) = "]" Then '字符“]”出现次数及位置
yn += 1
arrEi = i - 1
End If
Next
If zn = 1 And arrSi = 0 And yn = 1 Then '字符"["出现1次位置为0,字符" ] "出现1次
If str.Substring(arrEi + 1, 1) = "," Then '字符"]"后为","
arrstr += str.Substring(arrSi + 1, arrEi - arrSi - 1)
Dim a() As String = arrstr.Split(",").ToArray()
ReDim myarr(a.Length - 1)
For i As Integer = 0 To a.Length - 1 '得到数组(integer)
Dim ka As Integer = 0
Try
ka = CInt(a(i))
Catch ex As Exception
End Try
If ka <= 10000 And ka > 0 Then '数组超过限制
myarr(i) = ka
Else
mynum = -1
End If
Next
Else
mynum = -1
s = "输入错误"
End If
Try
aim = CInt(str.Substring(arrEi + 2)) '得到钱数
Catch ex As Exception
aim = 0
End Try
If aim > 0 And aim <= 100000 Then '钱数在范围内
Array.Sort(myarr) '数组排序(从小到大)
If myarr.Length >= 2 Then '数组是否有重复
For i As Integer = 0 To myarr.Length - 2
If myarr(i) = myarr(i + 1) Then
cf = True
End If
Next
End If
s += "不同面值的货币:" + arrstr + vbCrLf + "钱数:" + aim.ToString
If cf Then
mynum = -1
Else '数组不重复
For i = myarr.Length - 1 To 0 Step -1
If aim < myarr(i) Then
Else
mynum += CInt(aim \ myarr(i))
aim = aim Mod myarr(i)
If aim < myarr(0) And aim > 0 Then
aim += myarr(i)
mynum -= 1
End If
End If
Next
If aim > 0 Then mynum = -1 '如果零钱数大于零,无解
End If
Else
mynum = -1
s = "输入错误"
End If
Else
mynum = -1
s = "输入错误"
End If
Else
mynum = -1
s = "输入错误"
End If
MsgBox(s + vbCrLf + "最少货币数:" + mynum.ToString, vbOKOnly, "零钱兑换")
Else
MsgBox("没有输入!", vbOKOnly, "零钱兑换 ")
End If
End Sub
以上红色为主要算法,但有些解不出来。例如[5,12,3],21
求正解~!