Sharing my 0ms C++ solution


  • 0
    T
    class Solution {
    private:
        void combinationSum3Helper(int k, int n, int num, vector<vector<int>>& result, vector<int>&temp)
        {
            if(n==0 && k==0)
                result.push_back(temp);
            if(n<=0 || k<=0 || num>9)
                return;
                
            int i, count=0;
            while(count<=1 && count<=k && n-count*num>=0)
            {
                for(i=0; i<count; i++)
                    temp.push_back(num);
                combinationSum3Helper(k-count, n-count*num, num+1, result, temp);
                for(i=0; i<count; i++)
                    temp.pop_back();
                count++;
            }
        }
        
    public:
        vector<vector<int>> combinationSum3(int k, int n) {
            vector<int> temp;
            vector<vector<int>> result;
            combinationSum3Helper(k, n, 1, result, temp);
            
            return result;
        }
    };

Log in to reply
 

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