77 Combinations(组合数)

来源:互联网 发布:学生电脑软件下载 编辑:程序博客网 时间:2024/05/20 01:35

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

For example,
If n = 4 and k = 2, a solution is:

[  [2,4],  [3,4],  [2,3],  [1,2],  [1,3],  [1,4],]

这道题让求1到n共n个数字里k个数的组合数的所有情况,还是要用深度优先搜索DFS来解,根据以往的经验,像这种要求出所有结果的集合,一般都是用DFS调用递归来解。那么我们建立一个保存最终结果的大集合res,还要定义一个保存每一个组合的小集合out,每次放一个数到out里,如果out里数个数到了k个,则把out保存到最终结果中,否则在下一层中继续调用递归。根据上面分析,可写出代码如下:

class Solution {public:    vector<vector<int>> combine(int n, int k) {        vector<vector<int>> res;        vector<int> tmp;        dfs(tmp, res, n, k, 1);        return res;    }    void dfs(vector<int> &tmp, vector<vector<int>> &res, int n, int k, int i) {        if(tmp.size() == k) {             res.push_back(tmp);            return;        }        while(i <= n) {            tmp.push_back(i);            dfs(tmp, res, n, k, i+1);            tmp.pop_back();            ++i;        }    }};