[LeetCode] Combinations 组合项
2015-03-12 15:23
429 查看
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:
这道题让求1到n共n个数字里k个数的组合数的所有情况,还是要用深度优先搜索DFS来解,根据以往的经验,像这种要求出所有结果的集合,一般都是用DFS调用递归来解。那么我们建立一个保存最终结果的大集合res,还要定义一个保存每一个组合的小集合out,每次放一个数到out里,如果out里数个数到了k个,则把out保存到最终结果中,否则在下一层中继续调用递归。网友u010500263的博客里有一张图很好的说明了递归调用的顺序,请点击这里。根据上面分析,可写出代码如下:
对于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 题目讲解汇总(持续更新中...)
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 题目讲解汇总(持续更新中...)
相关文章推荐
- leetcode:Letter Combinations of a Phone Number(手机号码的字母组合)
- Leetcode:Combinations 组合
- LeetCode17——Letter Combinations of a Phone Number(手机几个按键对应的字母(符号)组合)
- LeetCode Letter Combinations of a Phone Number 经典组合问题
- Leetcode中的组合排列问题:Permutations,Combinations,Letter Combinations of a Phone Number
- LeetCode 17 Letter Combinations of a Phone Number(电话号码的字母组合)
- LeetCode Letter Combinations of a Phone Number 电话号码组合
- LeetCode-77 Combinations(组合)
- LeetCode-Letter Combinations of a Phone Number-电话号码字母组合-DFS
- [LeetCode] Letter Combinations of a Phone Number 电话号码的字母组合
- [LeetCode]-Letter Combinations of a Phone Number 电话键盘的字符串组合
- Letter Combinations of a Phone Number (电话号码字母组合) 【leetcode】
- leetcode——Letter Combinations of a Phone Number 手机按键字母组合(AC)
- [Leetcode] combinations 组合
- [LeetCode] Letter Combinations of a Phone Number 电话号码的字母组合
- leetcode-Combinations 复习复习排列组合
- Leetcode:Combinations 组合
- Letter Combinations of a Phone Number 电话按键字符的组合@LeetCode
- 【LeetCode】Permutations && Combinations 排列组合
- LeetCode 17 Letter Combinations of a Phone Number (电话号码字符组合)