77. Combinations

你快乐吗?

Posted by bbkgl on September 26, 2019

# 77. Combinations


dfs深搜,99%,需要处理一下的是剪枝,可以在一定程度上提高效率。

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> ans;
        vector<int> tpath;
        dfs(1, n, k, ans, tpath);
        return ans;
    }
    
    void dfs(int cur, int &n, int k, vector<vector<int>> &ans, vector<int> tpath) {
        if (k == 0) {
            ans.push_back(tpath);
            return ;
        } else {
            for (int i = cur; i <= n - k + 1; i++) {
                tpath.push_back(i);
                dfs(i + 1, n, k - 1, ans, tpath);
                tpath.pop_back();
            }
        }
    }
};