Use backtrack c++ solution, easy to understand.


  • 20
    Z
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> result;
        vector<int> path;
        backtrack(result, path, 1, k, n);
        return result;
    }
    
    void backtrack(vector<vector<int>> &result, vector<int> &path, int start, int k, int target){
        if(target==0&&k==0){
            result.push_back(path);
            return;
        }
        for(int i=start;i<=10-k&&i<=target;i++){
            path.push_back(i);
            backtrack(result,path,i+1,k-1,target-i);
            path.pop_back();
        }
    }

  • 1
    M

    can you explain this condtion i<=10-k


  • 0
    C

    it have k-1 number afer i,and the numbers in ascending order.


  • 1
    S

    @msai06 Do you understand this condtion i<=10-k now? i want to ask for your help.thank you


  • 0
    A

    @msai06 if target was less than 9,it cound shrik the range we should travel


Log in to reply
 

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