C++: 8ms simple backtracking solution


  • 0
    X
    class Solution {
    private:
        vector<vector<int>> res;
    public:
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            std::sort(candidates.begin(), candidates.end());
            int index = 0;
            vector<int> line;
            help(candidates, target, index, line);
            return res;
        }
        
        void help(vector<int>& candidates, int target, int index, vector<int> &line){
            if(target == 0) {
                res.push_back(line);
                return;
            }
            for(index; index<candidates.size() && candidates[index] <= target; index++){
                line.push_back(candidates[index]);
                help(candidates, target-candidates[index], index+1, line);
                line.pop_back();
                while(index+1!=candidates.size() && candidates[index]==candidates[index+1]) index++;
            }
        }
    };

Log in to reply
 

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