Combinations

方法一:使用深度遍历的方式,时间复杂度O(n!)

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> result;
        vector<int> path;
        dfs(n, k, 1, 0, path, result);
        return result;
    }
    
    void dfs(const int n, const int k, int start, int cur, vector<int> &path, vector<vector<int>> &result)
    {
        if(cur == k)
            result.push_back(path);
        
        for(int i=start; i<=n; ++i)
        {
            path.push_back(i);
            dfs(n, k, i+1, cur+1, path, result);
            path.pop_back();
        }
    }
};
posted @ 2017-05-11 20:36  chengcy  Views(130)  Comments(0)    收藏  举报