518、零钱兑换II:
class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
dp = [0] * (amount + 1)
dp[0] = 1
for i in range(len(coins)):
for j in range(coins[i], amount+1):
dp[j] += dp[j - coins[i]]
return dp[amount]
本题是完全背包求装满背包有多少种方法,求的是组合数,先遍历物品,再遍历背包
377、组合总和IV:
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] * (target + 1)
dp[0] = 1
for j in range(target+1):
for i in range(len(nums)):
if j >= nums[i]:
dp[j] += dp[j - nums[i]]
return dp[target]
本题是完全背包的求排列数,和上题不一样的是遍历顺序的选择,先遍历背包,再遍历物品,注意遍历背包的时候要从0开始