C++ Solution, NO Backtracking and clean


  • 0
    H

    class Solution {
    public:
    vector<vector<int>> combine(int n, int k) {
    vector<vector<int>> ans;
    vector<int> res;
    res.push_back(1);
    while(res.back() <= n){
    while(res.size() == k){
    ans.push_back(res);
    if(res.back() < n) res.back()++;
    else{
    int temp = res.back();
    while(temp == res.back()){
    res.pop_back();
    if(res.empty()) return ans;
    temp--;
    }
    res.back()++;
    }
    }
    res.push_back(res.back() + 1);
    }
    return ans;
    }
    };


Log in to reply
 

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