12-line C++ Backtracking Solution


  • 1
    L

    The idea is simple, just pick k elements increasingly. And I think my backtracking solution is quite concise.

    class Solution {
    public:
        vector<vector<int> > combine(int n, int k) {
            vector<vector<int>> res;
            vector<int> tmp;
            backtracking(n,k,res,tmp,1);
            return res;
        }
        
        void backtracking(int n, int k, vector<vector<int>>& res, vector<int>& tmp, int ind) {
            if(k==0)
                res.push_back(tmp);
            else
                for(int i=ind;i<=n;i++) {
                    tmp.push_back(i);
                    backtracking(n,k-1,res,tmp,i+1);
                    tmp.pop_back();
                }
        }
    };

  • 0
    Z

    Run Time Exceed Limit


Log in to reply
 

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