C++ solution for Combination Sum. 88%


  • 0
    G
    class Solution {
    public:
        vector<int> candidates2;
        vector<vector<int>> result;
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            sort(candidates.begin(),candidates.end());
            vector<int> combine;
            candidates2=candidates;
            combination(target,0, combine);
            return result;
        }
        
        void combination(int target, int start,vector<int> &combine){
            if(target==0){
                result.push_back(combine);
                return;
            }
            for(int i=start;i<candidates2.size();i++){
                if(target<candidates2[i])break;
                combine.push_back(candidates2[i]);
                combination(target-candidates2[i],i,combine);
                combine.pop_back();
            }
        }
    };

Log in to reply
 

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