8ms C++ solution with recursion


  • 0
    D
    class Solution {
    public:
        void combine_helper(int n, int m, int k, vector<int>* ans, vector<vector<int> >* res) {
            if (k == 0) {
                res->emplace_back(*ans);
                return;
            }
            for (int i = m; i <= n; ++i) {
                ans->emplace_back(i);
                this->combine_helper(n, i + 1, k - 1, ans, res);
                ans->pop_back();
            }
        }
    
        vector<vector<int> > combine(int n, int k) {
            vector<int> ans;
            vector<vector<int> > result;
            combine_helper(n, 1, k, &ans, &result);
            return result;
        }
        
    };

Log in to reply
 

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