Monday, October 20, 2014

Combination Sum

class Solution {
public:
     vector<vector<int>> combinationSum(vector<int> &candidates, int target) {
        vector<vector<int>> res;
        vector<int> com;
        sort(candidates.begin(),candidates.end());
        combinationSumRe(candidates,0,target,com,res);
        return res;
     }
//注意在实现中for循环中第一步有一个判断,那个是为了去除重复元素产生重复结果的影响,因为在这里每个数可以重复使用,所以重复的元素也就没有作用了,所以应该跳过那层递归。
 void combinationSumRe(vector<int> &candidates,int start, int target,vector<int>&com, vector<vector<int>>&res){
         if(target==0){
             res.push_back(com);return;
         }
         for(int i=start;i<candidates.size()&&target>=candidates[i];i++){
             if(i>0&&candidates[i]==candidates[i-1])continue;
             com.push_back(candidates[i]);
             combinationSumRe(candidates,i,target-candidates[i],com,res);
             com.pop_back();
         }
     }

};

No comments:

Post a Comment