题目:
给定一个数组arr,arr中所有的值都为正数且不重复,每个值代表一种面值的货币,每种面值的货币有无数张,再给定一个整数aim代表要找的钱数,求组成aim的最少货币数。
"""暴力递归"""
def minCoins(arr,aim):
if arr == None or len(arr) == 0:
return -1
return process(arr,0,aim)
def process(arr,i,rest):
if i == len(arr):
if rest == 0:
return 0
else:
return -1
k = 0
res = -1
while k*arr[i] < rest:
next_ = process(arr,i+1,rest-k*arr[i])
if next_ !=-1:
if res == -1:
res = next_ + k
else:
res = min(res,next_ + k)
k+=1
return res
"""动态规划"""
def minCoins1(arr, aim):
import sys
if arr == None or len(arr) == 0 or aim < 0:
return -1
row = len(arr)
dp = [[sys.maxsize for i in range(aim+1)] for j in range(row)]
for i in range(row):
dp[i][0] = 0
for j in range(1, aim+1):
if j % arr[0] == 0:
dp[0][j] = j // arr[0]
for i in range(1, row):
for j in range(1, aim+1):
left = sys.maxsize
if j - arr[i] >= 0 and dp[i][j-arr[i]] != sys.maxsize:
left = dp[i][j-arr[i]] + 1
dp[i][j] = min(left, dp[i-1][j])
return dp[row-1][aim] if dp[row-1][aim] != sys.maxsize else -1
minCoins1([5,2,3],20)