39 元素可重复选
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
可以重复选, 代表for j in range(start, n)
中, 下一个dfs起点可以是j, 这样代表了重复选择, 但是如何保证不会死循环呢, 就需要利用都是正数的条件了
python
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
def dfs(path, partial_sum, start):
if partial_sum > target:
return
if partial_sum == target:
ans.append(path[:])
return
for j in range(start, len(candidates)):
path.append(candidates[j])
dfs(path, partial_sum + candidates[j], j)
path.pop()
dfs([], 0, 0)
return ans
39 nums中有重复, 但每个只能选一次
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
只用添加两个改变, 横向去重和下一个的开始index会变为j + 1
python
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
candidates.sort()
def dfs(path, partial_sum, start):
if partial_sum > target:
return
if partial_sum == target:
ans.append(path[:])
return
for j in range(start, len(candidates)):
if j > start and candidates[j] == candidates[j - 1]:
continue
path.append(candidates[j])
dfs(path, partial_sum + candidates[j], j + 1)
path.pop()
dfs([], 0, 0)
return ans
377
输入: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)
python
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
dp = [1] + [0] * target
for i in range(1, len(dp)):
for num in nums:
if num > target:
continue
dp[i] += dp[i - num]
return dp[-1]