您的位置:首页 > 编程语言 > Python开发

[Leetcode]Combination Sum

2015-01-31 17:06 351 查看
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 (a1, a2,
… , 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 []
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode python