我正在尝试获取目标金额之和的所有硬币。我能够获得所需的硬币数量。我将如何解决它。
您可以无限使用相同的硬币
例如。 change([2], 10)
=> [2, 2, 2, 2, 2]
def change(coins, amount):
result = [amount+1] * (amount+1)
result[0] = 0
for i in range(1, amount+1):
for coin in coins:
if i >= coin:
result[i] = min(result[i], result[i-coin] + 1)
if result[amount] == amount+1:
return -1
return result[amount]
change([1, 2, 5,8], 7)
=> [5, 2]
顺序无关紧要。
答案 0 :(得分:2)
如果使用dyanmic programming
,则只能获得最佳结果,可以通过使用数组存储contentPadding
的中间结果来实现这一点,我已经根据您的dp版本进行了修改:>
dynamic programming
测试:
def change(coins, amount):
result = [amount+1] * (amount+1)
coins_results = [[] for _ in range(amount+1)]
result[0] = 0
for i in range(1, amount+1):
for coin in coins:
if i >= coin and result[i - coin] + 1 < result[i]:
result[i] = result[i-coin] + 1
coins_results[i] = coins_results[i-coin] + [coin]
if result[amount] == amount+1:
return []
return coins_results[amount]
输出:
print(change([1, 2, 5, 8], 7))
print(change([2], 10))
这是一个通过backtracking
输出所有结果的版本:
[5, 2]
[2, 2, 2, 2, 2]
测试:
def change(coins, amount):
res = []
def backtrack(end, remain, cur_result):
if end < 0: return
if remain == 0:
res.append(cur_result)
return
if remain >= coins[end]:
backtrack(end, remain - coins[end], cur_result + [coins[end]])
backtrack(end - 1, remain, cur_result)
backtrack(len(coins) - 1, amount, [])
return res
输出:
print(change([1, 2, 5, 8], 7))
print(change([2], 10))
希望对您有所帮助,如果还有其他问题,请发表评论。 :)
答案 1 :(得分:1)
我相信这是您要找的答案,请提出您的问题,以便我们对需要做的事情有更好的了解:)
def change(coins, amount):
ret = [] # Here we keep all possible solves
solves = [] # Here we keep all unique solves, to avoid duplicates (Eg.: [5, 2] and [2, 5] are both a solution to 7)
for c1 in coins:
for c2 in coins:
if c1 + c2 == amount: # Check if the solve is a match
solve = [c1, c2]
if not set(solve) in solves: # Check if the solve is not a duplicate
ret.append(solve)
solves.append(set(solve))
return ret # Return a list of solves
答案 2 :(得分:1)
如果要获取与目标数量相对应的所有组合,则可以使用以下生成器:
def change(coins, amount):
for i, coin in enumerate(coins):
if coin == amount:
yield (coin,)
elif coin < amount:
yield from ((coin,) + x for x in change(coins[i:], amount - coin))
print(list(change([2], 10))) # [(2, 2, 2, 2, 2)]
print(list(change([1, 2, 5, 8], 7))) # [(1, 1, 1, 1, 1, 1, 1), (1, 1, 1, 1, 1, 2), (1, 1, 1, 2, 2), (1, 1, 5), (1, 2, 2, 2), (2, 5)]