【leetcode】Combination Sum

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 (a1a2, … , 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]

利用递归搜索,同时剪枝就可以

 
 class Solution {

 public:

     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {

         sort(candidates.begin(),candidates.end());

         vector<vector<int> > result;

         vector<int> tmp;

         backtracking(result,candidates,target,tmp,,);

         return result;

     }

     void backtracking(vector<vector<int> > &result,vector<int> &candidates, int &target,vector<int> tmp, int sum,int index)

     {

         if(sum==target)

         {

             result.push_back(tmp);

             return;

         }

         else

         {

             int sum0=sum;

             //注意index

             for(int i=index;i<candidates.size();i++)

             {

                 tmp.push_back(candidates[i]);

                 sum=sum0+candidates[i];

                 if(sum>target)

                 {

                     break;

                 }

                 backtracking(result,candidates,target,tmp,sum,i);

                 tmp.pop_back();

             }            

         }        

     }

 };
上一篇:ABAP 使用的字符类型


下一篇:增强型for语句与java,c#的不同之处,with语句的使用