AC 9 line iterative solution(8ms)


  • 0
    W
    class Solution {
    public:
        vector<vector<int>> combine(int n, int k) {
            vector<vector<int>> result;
            vector<int> p(k , 0);
            for (auto i = 0; i >= 0;) {
                ++p[i];
                if (p[i] > n) --i;
                else if (i == k - 1) result.push_back(p);
                else p[i + 1] = p[i++];
            }
            return result;
        }
    };
    
    // Iteration details for combine(4, 2)
    
    // #start
    // 0 0
    // 1 0
    // 1 1
    // 1 2 push
    // 1 3 push
    // 1 4 push
    // 1 5
    // 2 5
    // 2 2
    // 2 3 push
    // 2 4 push
    // 2 5 
    // 3 5
    // 3 3
    // 3 4 push
    // 3 5 
    // 4 5
    // 4 4
    // 4 5
    // 5 5
    // 6 5
    // #stop

Log in to reply
 

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