My recursive cpp code


  • 0
    C
    class Solution {
    public:
    
        vector< vector<int> > result;
    
        void helper(vector<int>& candidates, int candidates_id, int target, vector<int> &res)
        {
            if(target < 0) return;
            
            if(target == 0)
            {
                result.push_back( vector<int>(res) );
                return;
            }
            
            if(candidates_id >= candidates.size()) return;
            if(candidates[candidates_id] > target) return;
            
            // choose candidates[candidates_id]
            res.push_back(candidates[candidates_id]);
            helper(candidates, candidates_id+1, target - candidates[candidates_id], res);
            res.pop_back();
            
            // not choose candidates[candidates_id]
            int tmp = candidates[candidates_id++];
            while(candidates_id < candidates.size() && candidates[candidates_id] == tmp)
                candidates_id++;
            helper(candidates, candidates_id, target, res);
        }
        
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target)
        {
            std::sort(candidates.begin(), candidates.end());
            
            vector<int> res;
            helper(candidates, 0, target, res);
    
            return result;
        }
    };`enter code here`

Log in to reply
 

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