【回溯】【leetcode题解】【M】【57】Combination Sum

175 篇文章 0 订阅
157 篇文章 0 订阅

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 


Subscribe to see which companies asked this question


详情见注释,两种写法,同一个思路


class Solution(object):
    count = 0

    '''
    def combinationSum(self, candidates, target):
        res = []
        candidates.sort()
        self.dfs(candidates, target, 0, [], res)
        return res

    def dfs(self, nums, target, index, path, res):
        #self.count += 1
        #print self.count
        if target < 0:
            return  # backtracking
        if target == 0:
            res.append(path)
            return
        for i in xrange(index, len(nums)):
            self.dfs(nums, target-nums[i], i, path+[nums[i]], res)

    '''

    def __init__(self):
        self.res = []
    def bt(self,c,temp,start,total,target):
        #print temp
        #self.count += 1
        #print self.count
        if total == target:
            self.res.append(temp)
            return
            #temp.sort()
            #if temp not in self.res:
            #    self.res.append(temp)
        else:
            for i in range(start,len(c)):
                if total + c[i] <= target:
                    #temp.append(c[i])#一个是,用append会非常慢,而且必须要用temp[:]指定,否则传值会出现错误
                    self.bt(c,temp+[c[i]],i,total+c[i],target)
                    #这里非常重要,这里面的start要改成i,不能每次都从零开始,否则会出现重复
                    #temp.pop(-1)#可能是,因为,这个不需要往回走,只需要往前看就行了,所以不用pop

    def combinationSum(self, candidates, target):

        c = candidates
        c.sort()
        #res = []
        #temp = []

        self.bt(c,[],0,0,target)
        self.res.sort()

        #print res
        return self.res


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值