Simple and clean C++ solution, backtracking


  • 0
    K
    class Solution {
    public:
    vector<vector<int>> res1;
    void backtrack(vector<int>& s,vector<int>& temp, int remain,int start,int count,int k) {
     if(remain < 0) return;
     else if(remain == 0 && temp.size()==k){
          res1.push_back(temp);
          count++;
     }
    else{
       for (int i = start;i < s.size();i++) {
    	temp.push_back(s[i]);
    	backtrack(s, temp,remain - s[i],i+1,count,k);
    	temp.pop_back();	
    	}
        }
    }
    vector<vector<int>> combinationSum3(int k, int target)  {
        vector<int> temp;
        vector<int> candidates{1,2,3,4,5,6,7,8,9};
        backtrack(candidates,temp,target,0,0,k);
        return res1;
     }
    };
    
    

Log in to reply
 

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