leetcode -- Combination Sum III -- 重点,dfs回溯模板

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

自己code重写

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值