c++ backtracking


  • 0
    B
    class Solution {
    public:
        vector<vector<int>> result;
        vector<int> cur;
        
        void dfs(vector<int> &candidates, int target, int start, int sum, vector<int> cur){
            if(sum==target) {
                result.push_back(cur); 
                return ;
            }
            
            for(int i=start;i<candidates.size();i++){
                if(sum+candidates[i]<=target) {
                    cur.push_back(candidates[i]);
                    dfs(candidates, target, i, sum+candidates[i], cur);
                    cur.pop_back();
                }
                
            }
            return;
        }
        
        vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
            if(!candidates.size()) return result;
            
            dfs(candidates, target, 0, 0, cur);
            
            return result;
        }
    };
    

Log in to reply
 

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