https://leetcode.com/problems/combination-sum-iii/
简单。总结自己的回溯模板
class Solution(object):
def dfs(self, candidates, start, end, target_val, subres, res):#输入参数
if sum(subres) == target:
res.append(subres[:])#这里注意要赋值,因为这里没有用stack,其实不复制也可以。但是养成好习惯
return
else:
i = start#第一个子节点
while i < end:
if sum(subres) + candidates[i] <= target_val:#试探第i个子节点是否满足约束条件,
self.dfs(candidates, i + 1, end, target, subres + [candidates[i]], res)
else:#如果不满足,因为是sorted candidates,所以可以忽略后面的子节点。相当于break
return
i += 1#不要忘记
def combinationSum3(self, k, n):
""" :type k: int :type n: int :rtype: List[List[int]] """
res = []
self.dfs(sorted(candidates), 0, 9, n, k, [], res)#这里candidates一定要sorted
return res
my code:
class Solution(object):
def dfs(self, candidates, start, end, target_val, target_lvl, subres, res):
if sum(subres) == target_val and len(subres) == target_lvl:
res.append(subres[:])
return
else:
i = start
while i < end:
if len(subres) + 1 <= target_lvl and sum(subres) + candidates[i] <= target_val:
self.dfs(candidates, i + 1, end, target_val, target_lvl, subres + [candidates[i]], res)
else:
return
i += 1
def combinationSum3(self, k, n):
""" :type k: int :type n: int :rtype: List[List[int]] """
res = []
self.dfs([x + 1 for x in xrange(9)], 0, 9, n, k, [], res)
return res
class Solution(object):
def dfs(self, depth, candidates, start, end, k, target, subres, res):
cur_sum = sum(subres)
if depth == k :
if cur_sum == target and subres not in res:
res.append(subres)
return
for i in xrange(start, end):
if cur_sum + candidates[i] <= target:#这里要有等于号
self.dfs(depth + 1, candidates, i+1, end, k, target, subres + [candidates[i]], res)
def combinationSum3(self, k, n):
""" :type k: int :type n: int :rtype: List[List[int]] """
candidates = [i + 1 for i in xrange(9)]
candidates.sort()
res = []
self.dfs(0, candidates, 0, len(candidates), k, n, [], res)
return res