My backtracking solution


  • 0
    E
    
    class Solution {
    public:
        void backtrack(vector<vector<int>> &res, vector<int> &s, int n, int k, int p){
            if (s.size() == k){
                res.push_back(s);
                return;
            }
            
            for (int i = p; i <= n; ++i){
                s.push_back(i);
                backtrack(res, s, n, k, i+1);
                s.pop_back();
            }
        }
        
        vector<vector<int>> combine(int n, int k) {
            vector<int> s;
            vector<vector<int>> res;
            backtrack(res, s, n, k, 1);
            return res;
        }
    };
    

Log in to reply
 

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