LC518. 零钱兑换 II:
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [0] * (amount + 1) #凑成总金额为j的货币组合为dp[j]
dp[0] = 1 #dp[0] 一定要等于1 否则后续无法进行递推公式
for i in range(len(coins)):
for j in range(coins[i], amount + 1):
dp[j] += dp[j - coins[i]] #求装满背包的递推公式中都是dp[j] += dp[j-nums[i]]
return dp[amount]
LC377. 组合总和 Ⅳ
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
dp = [0] * (target + 1) #凑成目标正整数为i的排列个数为dp[i]
dp[0] = 1
for i in range(1, target+1):
for j in nums:
#如果求组合数就是外层for循环遍历物品,内层for遍历背包
#如果求排列数就是外层for遍历背包,内层for循环遍历物品
if i >= j:
dp[i] += dp[i - j] #因为只要得到nums[j],排列个数dp[i - nums[j]],就是dp[i]的一部分
return dp[-1]