LeetCode#39 Combination Sum

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, a1a2 ≤ … ≤ 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,则不应该包括当前节点本身。

 1 # @param {integer[]} candidates
 2     # @param {integer} target
 3     # @return {integer[][]}
 4     def combinationSum(self, candidates, target):
 5         candidates.sort()
 6         res=[]
 7         self.cur(candidates, target, 0, [], res)
 8         return res
 9         
10     def cur(self, nums, target, index, localArr, res):
11         if target==0:
12             res.append(localArr[:])
13         else:
14             for i in range(index, len(nums)):
15                 nt=target-nums[i]
16                 if nt>=0:
17                     localArr.append(nums[i])
18                     self.cur(nums, nt, i, localArr, res)
19                     localArr.pop()
20                 else:
21                     break

 另外,在cur的for循环里,如果nt已经小于零,则不继续进行没必要的递归,也因为外围的 if-else 就不用处理target<0的情况了。

posted @ 2015-08-04 16:12  曾可爱  阅读(124)  评论(0编辑  收藏  举报