Just like subsets


  • 0
    H

    class Solution {
    public:
    void comb(vector<vector<int>> & res, vector<int> &path, vector<int> &nums, int k, int n, int pos){

        if(path.size() == k && n == 0){
            res.push_back(path);
            return;
        }
        if(n < 0 || path.size() > k){
            return;
        }
        
        for(int i = pos; i < nums.size(); ++i){
            
            path.push_back(nums[i]);
            comb(res, path, nums, k, n - nums[i], i + 1);
            path.pop_back();
        }
        
    }
    vector<vector<int>> combinationSum3(int k, int n) {
     
        vector<vector<int>> res;
           if(n <= 0 || n <= 0){
               return res;
           }
        vector<int> nums;
        for(int i = 1; i < 10; ++i){
            nums.push_back(i);
        }
        vector<int> path;
        comb(res, path, nums, k, n, 0);
    }
    

    };


Log in to reply
 

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