C++ solution for Combination


  • 0
    S

    class Solution {

    public:

    vector<vector<int>> combine(int n, int k) {
        vector<int> sub;
        vector<vector<int>> res;
        for (int i=1;i<=n;i++){
            sub.push_back(i);
            com(res, sub, n, k, i);
            sub.pop_back();
        }
        return res;
    }
    
    void com( vector<vector<int>> &res, vector<int> &sub, int n, int k, int start){
        if(sub.size()==k) {
            res.push_back(sub);
            return;
        }
        for (int j=start+1; j<=n;j++){
            sub.push_back(j);
            com(res, sub, n, k, j);
            sub.pop_back();
           
        }
    }
    

    };


Log in to reply
 

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