Reversed iterative C++ solution(8ms)


  • 0
    M
    class Solution {
    public:
        vector<vector<int>> combine(int n, int k) {
            vector<vector<int>> combs;
            vector<int> p(k);
            int i = k - 1;
            p.back() = n + 1;
    
            do {
                p[i]--;
                for (i--; i >= 0; i--) {
                    p[i] = p[i+1] - 1;
                }
                do {
                    combs.push_back(p);
                } while (--p.front() > 0);    
                for (i = 1; i < k && p[i] == i + 1; i++);
            } while (i != k);
    
            return combs;
        }
    };

Log in to reply
 

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