2 回答

TA贡献1824条经验 获得超8个赞
您的代码很好,问题在dp列表中。当您[[-1]*len(coins)]*(amount+1)在示例中执行此操作时,首先会创建一个列表,[-1, -1, -1]然后将其复制(通过引用)501次。当您更改任何列表中的任何项目时,所有其他列表也会更新,这将导致不正确的结果。
要解决此问题,请使用列表理解创建列表:
dp = [[-1 for _ in range(len(coins))] for _ in range(amount+2)]
或利用dictlookupO(1)在 Python 中的事实并使用dictfor memoization 以避免将来出现此类错误,例如:
dp = {}
def changeHelper(amount, coins, index):
if amount == 0:
return 1
if index<0:
return 0
if (amount, index) in dp:
return dp[(amount, index)]
total_ways = 0
if amount>=coins[index]:
total_ways = changeHelper(amount-coins[index], coins, index)
total_ways += changeHelper(amount, coins, index-1)
dp[(amount, index)] = total_ways
return dp[(amount, index)]
编辑:
这是为什么会发生的更多解释
>>> dp = [[-1] * 3] * 4
>>> dp
[[-1, -1, -1], [-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
>>> dp[0][0] = 5
>>> dp
[[5, -1, -1], [5, -1, -1], [5, -1, -1], [5, -1, -1]]
可以这样想,内部语句创建:
tmp = [-1, -1, -1]
然后是外面的:
dp = [tmp, tmp, tmp, tmp]

TA贡献1848条经验 获得超10个赞
这是您需要的 DP。
def change(amount, coins):
dp = [0] * (amount + 1)
dp[0] = 1
for x in range(amount + 1):
for c in coins:
if c > x: continue
dp[x] += dp[x - c]
return dp[amount]
添加回答
举报