16 lines concise and easy understand C++ solution backtracking


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

  • 0
    H

    very concise and easy understand.


Log in to reply
 

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