77. Combinations

dp...这个题目基本操作

class Solution {
private:
    int n;
public:
    vector> combine(int n, int k) {
        //vector v = {1, 2, 3};
        this->n = n;
        return comb(1, k);
    }
    vector> comb(int i, int k){
        vector> res;
        if (k == 0 || (n - i + 1) < k){
            return res;
        }
        if (k == 1){
            for(int j = i; j <= n; j++)
                res.push_back(vector(1, j));
            return res;
        }
        if (n - i + 1 == k){
            vector v;
            for(int j = i; j <= n; j++)
                v.push_back(j);
            res.push_back(v);
            return res;
        }
        auto v1 = comb(i + 1, k);
        auto v2 = comb(i + 1, k - 1);
        for(auto &vec : v2){
            vec.push_back(i);
            v1.push_back(vec);
        }
        return v1;
    }
};


你可能感兴趣的:(77. Combinations)