[leetcode 77] Combinations
来源:互联网 发布:新浪财经数据库 编辑:程序博客网 时间:2024/06/05 16:53
Question:
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],]
Subscribe to see which companies asked this question
如果N ==K和K==1不做解释;
一般情况N<K,时候,可以先求解(N-1,K-1)的情况,比如求(4,3)那么(3,2)的结果是:
【
【1,2】
【1,3】
【2,3】
】
对每一层的最后一个元素判断,比如第一层的最后一个元素为2,那么第一层后面可以添加3或者4;
第二层的最后一个元素是3,那么后面只能添加数据4;
第三层同样,只能添加4;
这样(4,3)的结果为:
【
【1,2,3】
【1,2,4】
【1,3,4】
【2,3,4】
】
代码如下:
<span style="font-size:14px;">class Solution {public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; if(n < k || k == 0) return res; if(n == k){ vector<int> temp; for(int i = 1; i <= n; ++i){ temp.push_back(i); } res.push_back(temp); return res; } if(k == 1){ // for(int i = 1; i <= n; ++i){ vector<int> temp(1,i); res.push_back(temp); } return res; } else{ vector<vector<int>> pre; pre = combine(n-1,k-1); for(int i = 0; i < pre.size(); ++i){ int len = pre[i].size(); for(int j = pre[i][len-1]+1; j <=n ; ++j){ vector<int> temp = pre[i]; temp.push_back(j); res.push_back(temp); } } return res; } }};</span>
0 0
- LeetCode 77 Combinations
- [leetcode 77] Combinations
- Leetcode NO.77 Combinations
- [leetcode] 77 Combinations
- [LeetCode 77]Combinations
- leetcode || 77、Combinations
- leetcode-77 Combinations
- LeetCode-77 Combinations(组合)
- Combinations - LeetCode 77
- leetcode 77:Combinations
- LeetCode(77) Combinations
- Leetcode #77 Combinations
- [leetcode-77]Combinations(java)
- leetcode 77: Combinations
- LeetCode(77) Combinations
- 【leetcode】【77】Combinations
- leetcode 77:Combinations
- 【LEETCODE】77-Combinations [Python]
- [翻译]angularjs 2.0官方新手入门教程(2)
- solr-in-action-ch1-Introduction to solr
- hdu 1176 免费馅饼
- HashMap嵌套HashMap嵌套HashMap(三层嵌套)
- js动态添加datagrid表头&批量保存实战研究
- [leetcode 77] Combinations
- Java 重写与重载区别 Java父类的Object方法 要重写tostring原因,多个catch处理逻辑
- UE4:编辑器中显示物体包围框
- [翻译]angularjs 2.0官方新手入门教程(3)
- leetcode:Counting Bits
- solr-in-action-ch4-Configuring Solr
- [翻译]angularjs 2.0官方新手入门教程(4)
- java堆排序递归代码,无原理版,比较好理解
- OKIO源码分析