题目
给出一个数组和目标值,找出所有的组合,使得组合里面元素的和为目标值。注意:原数组可能有重复元素;数组中的元素在组合里只能出现一次。如:
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]
Python题解
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates.sort()
path, res = [], []
self.dfs(candidates, target, 0, path, res)
return res
def dfs(self, candidates, target, index, path, res):
if target < 0:
return
if target == 0:
res.append(path[:])
for i in range(index, len(candidates)):
if i > index and candidates[i] == candidates[i - 1]:
continue
self.dfs(candidates, target - candidates[i], i + 1, path + [candidates[i]], res)