C++ solution, easy to understand


  • 0
    M
    class Solution {
    public:
        vector<vector<int>> combine(int n, int k) {
            vector<vector<int>>result;
            vector<int> array;
            helper(result, array, k, n, 1);
            return result;
        }
    private:
        void helper(vector<vector<int>>& result, vector<int>& array, int k, int n, int start)
        {
            if(array.size() == k)
            result.push_back(array);
            for(int i = start; i <= n; i++)
            {
                array.push_back(i);
                helper(result, array, k, n, i+1);
                array.pop_back();
            }
        }
    };

Log in to reply
 

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