leetcode--Combination Sum

1.题目描述

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] 

2.解法分析

实际上这是一个类似于深度搜索的算法,代码如下,

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int>cur;
        vector<vector<int>>result;
        int sum=0;
        sort(candidates.begin(),candidates.end());
10          myCombinationSum(candidates,cur,result,sum,0,target);
11          
12          return result;
13          
14      }
15      
16      void myCombinationSum(vector<int> &candidates,vector<int>&cur,vector<vector<int>>&result,int &curSum,int start,int target)
17      {
18          if(start>=candidates.size())return ;
19          for(int i=start;i<candidates.size();++i)
20          {
21              curSum+=candidates[i];
22              cur.push_back(candidates[i]);
23              if(curSum==target)
24              {//搜索到了满足要求的一条路径,那么按照之前的路径继续下移或右移肯定得不到另外满足的路径,因此只能上移
25                  result.push_back(cur);curSum-=candidates[i];
26                  cur.pop_back();break;
27              }
28              else 
29                  if(curSum<target)
30                  {
31                      myCombinationSum(candidates,cur,result,curSum,i,target);
32                      curSum-=candidates[i];
33                      cur.pop_back();
34                  }
35                  else
36                  {
37                      curSum-=candidates[i];
38                      cur.pop_back();
39                      break;
40                  }    
41          }
42          
43      }
44  };
原文地址:https://www.cnblogs.com/obama/p/3287857.html