Sharing my 12ms C++ solution


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

Log in to reply
 

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