Recursive solution in c++ ,8ms


  • 0
    A
    class Solution {
    public:
        vector<vector<int>> combine(int n, int k) {
            vector<vector<int>> result;
            vector<int> vec;
            helper(1,n,k,vec,result);
            return result;
        }
        
        void helper(int first,int last,int k,vector<int> & vec,vector<vector<int>> & result)
        {
            if(k==0)
            {
                result.push_back(vec);
                return ;
            }
    
            for(int i=first;i<=last-k+1;i++)
            {
                vec.push_back(i);
                helper(i+1,last,k-1,vec,result);
                vec.pop_back();
            }
        }
    
    };

Log in to reply
 

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