[Leetcode]Combination Sum

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]

还是用DFS~helper函数中for循环里有判断重复元素,是为了避免产生重复的结果,因为这里每个元素都可以重复使用~还有值得注意的是,递归中当remainder == 0 时 加到结果集中的是item[:],而不是直接用item(item[:]返回的是item的拷贝);因为这个item到其他递归层中还要用,如果直接用这个等会他会被改变, 这样加进去的也就不对了

class Solution:
    # @param candidates, a list of integers
    # @param target, integer
    # @return a list of lists of integers
    def combinationSum(self, candidates, target):
        if candidates is None or len(candidates) == 0: return []
        self.res = []
        candidates.sort()
        self.helper(candidates, 0, target, [])
        return self.res
        
    def helper(self, candidates, start, remainder, item):
        if remainder < 0: return
        if remainder == 0:
            self.res.append(item[:])
            return
        for i in xrange(start, len(candidates)):
            if i > 0 and candidates[i] == candidates[i - 1]:
                continue
            item.append(candidates[i])
            self.helper(candidates, i, remainder - candidates[i], item)
            item.pop()

还有一种解法,动态规划,runtime要比上一种解法短~

class Solution:
    # @param candidates, a list of integers
    # @param target, integer
    # @return a list of lists of integers
    def combinationSum(self, candidates, target):
        if candidates is None or len(candidates) == 0: return []
        dp = {}; dp[0] = [[]]
        for i in xrange(1, target + 1):
            dp[i] = []
            for num in candidates:
                # dp[i-num] means it's not empty
                if i >= num and dp[i-num]: 
                    for L in dp[i-num]:
                        tmp = sorted(L + [num])
                        if tmp not in dp[i]:
                            dp[i].append(tmp)                  
        # return [] is possible, e.g. candidates = [2], target = 1 
        return dp[target] if target in dp else []


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值