您的位置:首页 > 其它

LeetCode#39 Combination Sum

2015-08-04 16:12 295 查看
Problem Definition:

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]


Solution:

回溯法(DFS)。每个元素可以被重复用很多次,因此DFS时子节点应当包括当前节点本身(或者说是再构造一个新的节点,包含了当前元素)。

另一个问题 Combination Sum,则不应该包括当前节点本身。

# @param {integer[]} candidates
# @param {integer} target
# @return {integer[][]}
def combinationSum(self, candidates, target):
candidates.sort()
res=[]
self.cur(candidates, target, 0, [], res)
return res

def cur(self, nums, target, index, localArr, res):
if target==0:
res.append(localArr[:])
else:
for i in range(index, len(nums)):
nt=target-nums[i]
if nt>=0:
localArr.append(nums[i])
self.cur(nums, nt, i, localArr, res)
localArr.pop()
else:
break


另外,在cur的for循环里,如果nt已经小于零,则不继续进行没必要的递归,也因为外围的 if-else 就不用处理target<0的情况了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: