代码随想录 Leetcode39. 组合总和

题目:

代码随想录 Leetcode39. 组合总和_第1张图片


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

class Solution {
public:
    vector> res;
    vector path;
    
    void backtracking(vector& candidates, int target, int startIndex) {
        if (target == 0) {
            res.push_back(path);
            return;   
        }
        for (int i = startIndex; i < candidates.size(); ++i) {
            target -= candidates[i];
            if (target < 0) break;
            path.push_back(candidates[i]);
            backtracking(candidates, target, i);
            path.pop_back();
            target += candidates[i];
        }
        return;
    }
    vector> combinationSum(vector& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        backtracking(candidates, target, 0);
        return res;
    }
};

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