Leetcode 77 Solution

This article provides solution to leetcode question 77 (combinations)

https://leetcode.com/problems/combinations

Solution

class Solution {
    vector<int> res;
    vector<vector<int>> m_res;

public:
    void generate(vector<int>& a, int start, int k)
    {
        if (res.size() == k)
        {
            m_res.push_back(res);
            return;
        }

        for (int i = start; i < a.size(); i++)
        {
            res.push_back(a[i]);
            generate(a, i + 1, k);
            res.pop_back();
        }
    }

    vector<vector<int>> combine(int n, int k) {
        vector<int> a;
        for (int i = 1; i <= n; i++)
            a.push_back(i);

        generate(a, 0, k);

        return m_res;
    }
};