我正在做这道题https://leetcode.com/problems/coin-change-2/。给定数量和面额,我需要找到多种更改硬币的方法。
我想出了一个解决方案来尝试每种可能的金额面额,如果以前见过,就缓存它。
class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
dp = [[-1]*len(coins)]*(amount+1)
def changeHelper(amount, coins, index):
if amount == 0:
return 1
if index<0:
return 0
if dp[amount][index]!=-1:
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]
return changeHelper(amount, coins, len(coins)-1)
我得到了错误的答案,并且花了几个小时来找出错误。
Test case
500
[1,2,5]
expected answer 12701
my output 301
有只小跳蛙
慕桂英546537
相关分类