您的位置:首页 > 其它

[LeetCode] Combinations 组合项

2015-03-12 15:23 393 查看
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保存到最终结果中,否则在下一层中继续调用递归。网友u010500263的博客里有一张图很好的说明了递归调用的顺序,请点击这里。根据上面分析,可写出代码如下:

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


对于n = 5, k = 3, 处理的结果如下:

1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5

LeetCode All in One 题目讲解汇总(持续更新中...)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: