C++ solution DP. 28ms


  • -2
    L

    class Solution {

    public:

    vector<vector<int>> result;
    
    vector<int> temp;
    
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        
        sort(candidates.begin(), candidates.end());
        
        combinationSumGene(candidates, target, 0, candidates.size());
        return result;
    }
    
    void combinationSumGene(vector<int>& candidates, int target, int l, int r) {
        
        if (target == 0) {
            result.push_back(temp);
            return;
        }
        
        if (l>=r || target<0) {
            return;
        }
        
        for (int i = l; i<r; i++) {
            temp.push_back(candidates[i]);
            combinationSumGene(candidates, target-candidates[i], i, r);
            temp.pop_back();
        }
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.