LC 77 Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.


Input: n = 4, k = 2


In this problem, we will use recursive function recur that will recursively call itself with different **starting position ** and push the current result to solution when the current result’s size is k.

For n = 3

                              recur[] start = 0 
        /                                |                              \

    recur[1], start = 1           recur[2], start = 2                 recur[3], start = 3
      /       \                          |

r[1, 2] s=2  r[1,3] s = 3              r[2,3] s=3

When each recursive call is finished, we pop the res vector so it will resort to what res was before the call and avoid repeatedly allocate vectors.

class Solution {
    recusrive funtion recur(partialConb, input) will call
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> sol;
        vector<int> res;
        recurse(res, 0, k,n, sol);
        return sol;

    void recurse(vector<int>& res, int start, int k, int n, vector<vector<int>>& sol){
        if(res.size() == k){
            //cout<<"here with"<< res[0] <<res[1]<<"\n";
        for(int i = start; i < n; i ++){
            //cout<<"pushing "<<i + 1<< "on size"<<res.size()<<"\n";
            res.push_back(i + 1);

            recurse(res, i + 1, k, n, sol);
            //cout<<"after pop"<<res.size()<<"is size\n";

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see