leetcode: Combination Sum

http://oj.leetcode.com/problems/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 (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] 

思路

显然是递归,注意两点:

  1. 数字可以重复使用。
  2. 结果里面不能有重复,比如[2, 2, 4, 5]的情况,第1个2用过以后循环直接跳到4。
 1 class Solution {
 2 public:
 3     void internalCombinationSum(vector<int> &candidates,
 4             int start,
 5             int sum,
 6             int target,
 7             vector<int> &combination,
 8             vector<vector<int> > &result) {
 9         int size = candidates.size();
10         
11         if (sum == target) {
12             result.push_back(combination);
13             
14             return;
15         }
16         else if ((start >= size) || (sum > target)) {
17             return;
18         }
19 
20         for (int i = start; i < size; ) {
21             int v = candidates[i];
22             
23             combination.push_back(v);
24             internalCombinationSum(candidates, i, sum + v, target, combination, result);
25             combination.pop_back();
26 
27             int j = i + 1;
28             
29             while (j < size) {
30                 if (candidates[i] == candidates[j]) {
31                     ++j;
32                 }
33                 else {
34                     break;
35                 }
36             }
37             
38             i = j;
39         }
40     }
41     
42     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
43         vector<vector<int> > result;
44         vector<int> combination;
45         
46         sort(candidates.begin(), candidates.end());
47         internalCombinationSum(candidates, 0, 0, target, combination, result);
48            
49         return result;
50     }
51 };

 

posted @ 2013-11-04 18:11  移山测试工作室黑灯老师  阅读(785)  评论(0编辑  收藏  举报
count website visits
Buy Computers