背包问题
详细讲解请见 -> 代码随想录
最近做的几道题目总结
根据所给的数组nums[]
中,找出满足条件(目标和)的目标值 target
从 nums 中找出并返回总和为 target 的元素的最少组合,没有返回-1
数组中的数字不可以重复出现
nums = [1,2,3], target = 6
输出:2
解释:两个3的和为6
(3, 3)
def combinationSum(self, nums: List[int], target: int) -> int:
dp = [inf] * (target+1)
dp[0] = 0
for num in nums:
for c in range(num , target+1):
dp[c] = min(dp[c], dp[c-num ]+1)
ans = dp[target]
return ans if ans < inf else -1
从 nums 中找出并返回总和为 target 的元素组合的个数(数组元素可以不唯一)
数组中的数字不可以重复出现
nums = [1,2,3], target = 4
输出:4
解释:
(1, 3)
def combinationSum(self, nums: List[int], target: int) -> int:
dp = [0]*(target+1)
dp[0] = 1
for num in nums:
for c in range(target, num-1, -1):
dp[c] += dp[c-num]
return dp[target]
从 nums 中找出并返回总和为 target 的元素组合的个数(数组元素唯一)
数组中的数字可以重复出现,[1 1 2]和[1 2 1]算一种情况
nums = [1,2,3], target = 4
输出:4
解释:
(1, 1, 1, 1)
(1, 1, 2)
(1, 3)
(2, 2)
def combinationSum(self, nums: List[int], target: int) -> int:
n = len(nums)
dp = [0] * (target+1)
dp[0] = 1
for num in nums:
for c in range(num, target+1):
dp[c] += dp[c-num]
return dp[target]
从 nums 中找出并返回总和为 target 的元素组合的个数(数组元素唯一)
数组中的数字可以重复出现,(1 1 2)和(1 2 1)算两种情况
nums = [1,2,3], target = 4
输出:7
解释:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
class Solution:
def combinationSum(self, nums: List[int], target: int) -> int:
n = len(nums)
dp = [0] * (target+1)
dp[0] = 1
for i in range(target+1):
for num in nums:
if i >= num: dp[i] += dp[i-num]
return dp[target]