Simple and Clear C++ Solution


  • 0
    C
       class Solution {
    public:
        vector<vector<int> > combine(int n, int k) {
            vector<vector<int> > ret;
            vector<int> temp;
            backtracking(n,k,1,ret,temp);
            return ret;
        }
        void backtracking(int n,int k,int index,vector<vector<int> > &ret,vector<int> temp){
            if(k==0)
            ret.push_back(temp); 
            for(int i=index; i<n+1 ;++i){
                if(i!=index)
                    temp.pop_back();
                temp.push_back(i);
                backtracking(n,k-1,i+1,ret,temp);
            }
        }
    };

Log in to reply
 

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