12ms recursive c++


  • 3
    G
    class Solution {
    public:
        vector<vector<int> > combine(int n, int k) {
            vector<vector<int> > rslt;
            vector<int> path(k, 0);
            combine(n, k, rslt, path);
            return rslt;
        }
    private:
        void combine(int n, int k, vector<vector<int> > &rslt, vector<int> &path) {
            if (k == 0) {
                rslt.push_back(path);
                return;
            }
            for (int i = n; i >= 1; i--) {
                path[k - 1] = i;
                combine(i - 1, k - 1, rslt, path);
            }
        }
    };

  • 0
    J

    clean and easy to understand. Search it backward makes it much cleaner. Thanks for sharing.


  • 1
    C

    I think you can modify the condition of the loop a little bit to make the program run faster. When k > n, the function combine(n, k rslt, path) won't do anything. So we can change the condition of the loop like:
    for (int i = n; i >= k; i--)


Log in to reply
 

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