19 lines concise and easy understand c++ solution backtracking


  • 3
    A
    class Solution {
    public:
        vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
            sort(candidates.begin(), candidates.end());
            vector<vector<int>> res;
            vector<int> tmp;
            backtracking(res, candidates, tmp, 0, target);
            return res;
        }
        void backtracking(vector<vector<int>>& res, vector<int>& candidates, vector<int> tmp, int index, int target){
            if(target < 0 )return;
            if(target == 0){
                res.push_back(tmp);
                return;
            }
            for(int i = index; i < candidates.size(); i++){
                if(i == index || candidates[i] != candidates[i - 1]){
                    tmp.push_back(candidates[i]);
                    backtracking(res, candidates, tmp, i + 1, target - candidates[i]);
                    tmp.pop_back();
                }
            }
        }
    };

Log in to reply
 

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