leetcode-----39. 组合总和

代码(dfs)

class Solution {
public:
    vector<vector<int>> ans;
    vector<int> path;

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        dfs(candidates, 0, target);
        return ans;    
    }

    void dfs(vector<int> cs, int u, int target) {
        if (target == 0) {
            ans.push_back(path);
            return;
        }
        if (u == cs.size()) return;

        for (int i = 0; cs[u] * i <= target; ++i) {
            dfs(cs, u + 1, target - cs[u] * i);
            path.push_back(cs[u]);
        }
        for (int i = 0; cs[u] * i <= target; ++i) {
            path.pop_back();
        }
    }
};
原文地址:https://www.cnblogs.com/clown9804/p/13254932.html