[40][中等][回溯] 组合总和 II
题目描述
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]题目描述
最后更新于
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[5]
]最后更新于
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
n = len(candidates)
results = []
candidates.sort()
def dfs(path, t, start):
if t < 0:
return
if t == 0:
results.append(path[:])
seen = set()
for i in range(start, n):
if candidates[i] in seen:
continue
seen.add(candidates[i])
path.append(candidates[i])
dfs(path, t - candidates[i], i + 1)
path.pop()
dfs([], target, 0)
return results