码迷,mamicode.com
首页 > 其他好文 > 详细

39. Combination Sum I/II

时间:2018-09-07 11:01:19      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:vector   情况   color   sort   res   begin   continue   push   solution   

基础backtracing题,先排序一下,每次传一个参数表示开始的下标。

class Solution {
public:
    vector<vector<int>> res;
    
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        vector<int> tmp;
        dfs(candidates, target, tmp, 0);
        return res;
    }
    
    void dfs(vector<int>& candidates, int target, vector<int> &tmp, int start){
        if (target<0) return;
        if (target==0) res.push_back(tmp);
        for (int i=start;i<candidates.size();++i){
            tmp.push_back(candidates[i]);
            dfs(candidates,target-candidates[i],tmp,i);
            tmp.pop_back();
        }
    }
};

 

40. Combination Sum II

有重复元素的情况。和Permutation II处理方法类似,如果 i>start && candidates[i] == candidates [i-1] , 说明当前元素是这层dfs的重复元素,不需要再对candidates[i]进行递归了。

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> cur;
        sort(candidates.begin(),candidates.end());
        dfs(candidates,target,res,cur,0);
        return res;
    }
    
    void dfs(vector<int>& candidates, int target, vector<vector<int>> &res, vector<int> &cur, int start){
        if (target<0) return;
        if (target==0) res.push_back(cur);
        for (int i=start;i<candidates.size();++i){
            if (i>start && candidates[i]==candidates[i-1]) continue;
            cur.push_back(candidates[i]);
            dfs(candidates,target-candidates[i],res,cur,i+1);
            cur.pop_back();
        }
    }
};

 

39. Combination Sum I/II

标签:vector   情况   color   sort   res   begin   continue   push   solution   

原文地址:https://www.cnblogs.com/hankunyan/p/9602329.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!