LeetCode 39. 组合总和(C++)



实现:深度优先搜索

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        DFS(0,0,target,candidates.size(),candidates);
        return total;
    }
private:
    vector<vector<int> > total;
    vector<int> temp;
    void DFS(int index,int sum,int target,int n,vector<int>& candidates){
        if(sum==target) {
            total.push_back(temp);
            return;
        }
        if(sum > target) return;
        for(int i = index;i<candidates.size();i++){
            temp.push_back(candidates[i]);
            DFS(i,sum+candidates[i],target,n,candidates);
            temp.pop_back();          
        }
    }
};
posted @ 2020-09-09 21:27  是水泵呢  阅读(141)  评论(0编辑  收藏  举报