Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7]
and target 7
,
A solution set is:
[
[7],
[2, 2, 3]
]
一般跟求combiantion相关的题目基本上都会用到DFS。这里需要注意的是,用L22可以代替L23-L25。因为L22并没有改变 line, 所以line+[x]在内存中其实被另外的单独存储,所以不用line.pop()。
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort() res = []
line = []
self.helper(candidates, target, res, line)
return res def helper(self, candidates, target, res, line):
if target == 0:
res.append([x for x in line])
return for i, x in enumerate(candidates):
if x <= target:
# self.helper(candidates[i:], target-x, res, line+[x])
line.append(x)
self.helper(candidates[i:], target-x, res, line)
line.pop()