代码随想录 Leetcode40.组合总和 II

题目:

代码随想录 Leetcode40.组合总和 II_第1张图片


代码(首刷看解析 2024年2月1日):

class Solution {
public:
    vector> res;
    vector path;
    void backtracking(vector& candidates, int target, int startIndex, vector& used) {
        if (target == 0) {
            res.push_back(path);
            return;
        }
        for (int i = startIndex; i < candidates.size(); ++i) {
            if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) continue;
            target -= candidates[i];
            if (target < 0) return;
            path.push_back(candidates[i]);
            used[i] = true;
            backtracking(candidates, target, i + 1, used);
            used[i] = false;
            path.pop_back();
            target += candidates[i];
        }
        return;
    }
    vector> combinationSum2(vector& candidates, int target) {
        vector used(candidates.size(),0);//used用来辨别使用过的元素
        sort(candidates.begin(), candidates.end());
        backtracking(candidates, target, 0, used);
        return res;
    }
};

你可能感兴趣的:(#,leetcode,---medium,前端,算法,javascript)