题目:零钱兑换2
题解:
1)对于完全背包问题,同一件物品拿取的次数可以是无数次
2)先遍历物品,然后是背包。在遍历背包的时候,正序遍历的时候,每个物品可以放多次,但是倒叙遍历,每个物品只能放一次。
3)对于完全背包,先遍历物品还是背包都是ok的
4)所以递推公式:dp[j] += dp[j - coins[i]];
这个递推公式大家应该不陌生了,在讲解01背包题目的时候在这篇494. 目标和 (opens new window)中就讲解了,求装满背包有几种方法,公式都是:dp[j] += dp[j - nums[i]];
代码:
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]
题目:组合总和2
题解:
1)先遍历背包,再遍历物品,求的是排列数;先遍历物品,再遍历背包,求的是组合数。
代码:
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 i in range(1, target+1):
for n in nums:
if i >= n:
dp[i] += dp[i - n]#迭代函数要注意
return dp[target]