240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 14 | Leetcode 39. Combination Sum

题解

Medium | Backtracking

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> sols;
        vector<int> sol;
        helper(candidates, target, 0, 0, sol, sols);
        return sols;
    }
    
    void helper(vector<int>& candidates, int target, int index, int sum, vector<int>& sol, vector<vector<int>>& sols) {
        if(sum == target) {
            sols.push_back(sol);
            return;
        }
        
        if(sum > target) return;
        
        for(int i = index; i < candidates.size(); i++) {
            sol.push_back(candidates[i]);
            helper(candidates, target, i, sum+candidates[i], sol, sols);
            sol.pop_back();
        }
    }
};
posted @ 2020-09-29 12:00  CasperWin  阅读(69)  评论(0编辑  收藏  举报