39. 组合总和/C++

39. 组合总和/C++_第1张图片
标准回溯法

class Solution {
private:
    vector<vector<int>> res;
    vector<int> row;
    
    void combination(vector<int>& candidates, int target, int index){
    	//不符合条件,返回
        if(target<0)
            return;
        //符合条件,将row加入res,返回
        if(target==0){
            res.push_back(row);
            return;
        }
        else{
        	//从第index个数开始处理,候选解为index及以后的元素
            for(int i=index;i<candidates.size();++i){
                row.push_back(candidates[i]);
                combination(candidates,target-candidates[i],i);
                //回溯
                row.pop_back();
            }
        }    
    }
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        res.clear();
        row.clear();
        if(candidates.empty())
            return res;
        
        combination(candidates,target,0);
        return res;
    }
};

你可能感兴趣的:(回溯法,LeetCode/C++)