Leetcode 40. 组合总和 II

和Leetcode39一样,只是从原来的无限个一样的数到有限个一样的数

class Solution {
public:
    vector<vector<int>> ans;
    vector<int> val;
    void dfs(vector<int>& candidates, int target, int index) {
        if (target == 0) {
            ans.push_back(val);
            return;
        }
        if (index == candidates.size()) return;
        int i = 0, n = 1;
        while (index + 1 != candidates.size() && candidates[index + 1] == candidates[index]) ++index, ++n;
        while (++i*candidates[index] <= target);
        int k = min(i - 1, n);
        for (int i = 0; i < k; ++i) val.push_back(candidates[index]);
        for (; k >= 0; --k) {
            dfs(candidates, target - k * candidates[index], index + 1);
            if (k) val.pop_back();
        }
    }
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        dfs(candidates, target, 0);
        return ans;
    }
};

你可能感兴趣的:(Leetcode 40. 组合总和 II)