leetcode-----40. 组合总和 II

代码(dfs)

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

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        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;

        int k = u + 1;
        while (k < cs.size() && cs[k] == cs[u]) k++;
        int cnt = k - u;
        
        for (int i = 0; cs[u] * i <= target && i <= cnt; ++i) {
            dfs(cs, k, target - cs[u] * i);
            path.push_back(cs[u]);    
        }

        for (int i = 0; cs[u] * i <= target && i <= cnt; ++i) {
            path.pop_back();
        }
    }
};
posted @ 2020-07-06 15:24  景云ⁿ  阅读(46)  评论(0编辑  收藏  举报