My recursive cpp code


  • 0
    C
    class Solution {
    public:
    
        vector< vector<int> > result;
        
        void helper(int k, int cur, int n, vector<int> &res)
        {
            if(n < 0 || k < 0) return;
            
            if(!n && !k)
            {
                result.push_back( vector<int>(res) );
                return;
            }
            
            if(cur > n || cur > 9) return;
            
            // choose cur
            res.push_back(cur);
            helper(k-1, cur+1, n-cur, res);
            res.pop_back();
            
            // not choose cur
            helper(k, cur+1, n, res);
        }
    
        vector<vector<int>> combinationSum3(int k, int n) 
        {
            vector<int> res;
            helper(k, 1, n, res);
            
            return result;
        }
    };

Log in to reply
 

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