LeetCode Day61 combination

回溯

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        vector<int> out;
        DFS(res,out,1,k,n);
        return res;
    }
    void DFS(vector<vector<int>>& res,vector<int>& out,int start,const int& k,const int& n){
        if(out.size()==k) res.push_back(out);
        for(int i=start;i<=n;i++){
            out.push_back(i);
            DFS(res,out,i+1,k,n);
            out.pop_back();
        }
    }
};

C(n,k)=C(n-1,k-1)+C(n-1,k)

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        if (k > n || k < 0) return {};
        if (k == 0) return {{}};
        vector<vector<int>> res=combine(n-1,k-1);
        for(auto &a:res) a.push_back(n);
        for (auto &a : combine(n - 1, k)) res.push_back(a);
        return res;
    }
};

0 0 #initialization
1 0
1 1
1 2 #push_back
1 3 #push_back
1 4 #push_back
1 5
2 5
2 2
2 3 #push_back
2 4 #push_back

3 4 #push_back
3 5
4 5
4 4
4 5
5 5 #stop

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        vector<int> out(k,0);
        int i=0;
        while(i>=0){
            out[i]++;
            if(out[i]>n)i--;
            else if(i==k-1) res.push_back(out);
            else out[++i]=out[i-1];
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41394379/article/details/85261697