回溯法1

candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

class Solution:
def combinationSum2(self, candidates: List[int], target: int):
if not candidates:
return []
candidates.sort()
n = len(candidates)
res = []

def backtrack(i, tmp_sum, tmp_list):
if tmp_sum == target:
res.append(tmp_list)
return
for j in range(i, n):
if tmp_sum + candidates[j] > target : break
if j > i and candidates[j] == candidates[j-1]:continue
backtrack(j + 1, tmp_sum + candidates[j], tmp_list + [candidates[j]])
backtrack(0, 0, [])
return res

回溯就是递归

变量是起点0 总和0 列表

树的结构用条件去除多余的分支

posted @ 2019-07-16 23:33  呼呼嘻嘻  阅读(138)  评论(0编辑  收藏  举报