My Recursive solution


  • 0
    B
    class Solution {
    public:
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            vector<vector<int>> ret,call_back;
            for(int i = 0;i < candidates.size();i++){
                if(candidates[i] == target){
                    ret.push_back({candidates[i]});
                }else if(candidates[i] < target){
                    call_back = combinationSum(candidates,target-candidates[i]);
                    if(call_back.size()){
                        for(int j = 0;j < call_back.size();j++){
                            if(candidates[i] > call_back[j][0]) 
                                continue;
                            
                            vector<int> v;
                            v.push_back(candidates[i]);
                            v.insert(v.end(),call_back[j].begin(),call_back[j].end());
                            ret.push_back(v);
                        }
                    }
                }
            }
            return ret;
        }
    };
    

Log in to reply
 

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