题目链接: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] 

这道题的要求是给定一组候选数字C和目标数字T,找到所有C中数字的组合,使其和为T。数字可以重复被选。

备注:所有候选数字全为正数,要以非递减方式返回数字组合,结果不包含重复元素。

这道题要求返回所有情况,这是一个NP问题,可以通过回溯方式,逐个找到所有情况。下面是递归处理的代码,可以看到第28、29、30行,就是熟悉的递归回溯代码哦。

时间复杂度:O(???)

空间复杂度:O(nm)(结果数量)

 1 class Solution
 2 {
 3     vector<vector<int> > vvi;
 4 public:
 5     vector<vector<int> > combinationSum(vector<int> &candidates, int target)
 6     {
 7         sort(candidates.begin(), candidates.end());
 8         
 9         vector<int> vi;
10         combinationSum(candidates, target, 0, vi);
11         return vvi;
12     }
13     
14 private:
15     void combinationSum(vector<int> &candidates, int target, int i, vector<int> &vi)
16     {
17         if(target == 0)
18         {
19             vvi.push_back(vi);
20             return;
21         }
22 
23         for(int j = i; j < candidates.size(); ++ j)
24         {
25             if(target < candidates[j])
26                 break;
27 
28             vi.push_back(candidates[j]);
29             combinationSum(candidates, target - candidates[j], j, vi);
30             vi.pop_back();
31         }
32     }
33 };