您的位置:首页 > 其它

[leetcode 77] Combinations

2016-04-21 23:33 246 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: