C++ recursive solution


  • 0
    J
    vector<vector<int>> combinationSum3(int k, int n) {
        vector<vector<int>> result; vector<int> r;
        combinationSum3(result, r, 1, k, n);
        return result;
    }
    
    void combinationSum3(vector<vector<int>>& result, vector<int>& r, int level, int k, int n) {
        int sum = accumulate(r.begin(), r.end(), 0);
        if(k == r.size() && sum == n) 
            result.push_back(r);
        else if(k > r.size()) {
            for(int i = level; i<= 9; i++) {
                if(sum + i > n)
                    return;
                
                r.push_back(i);
                combinationSum3(result, r, i + 1, k, n);
                r.pop_back();
            }
        }
    }

Log in to reply
 

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