您的位置:首页 > 其它

[77]Combinations

2015-10-27 15:55 183 查看
【题目描述】

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],
]

【思路】
dfs+递归。

【代码】

class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> ans;
vector<int> path;
dfs(n,k,1,0,ans,path);
return ans;
}
void dfs(int n,int k,int start,int cur,vector<vector<int>>& ans,vector<int>& path){
if(cur==k){
ans.push_back(path);
}
for(int i=start;i<=n;i++){
path.push_back(i);
dfs(n,k,i+1,cur+1,ans,path);
path.pop_back();
}
}
};

class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> ans;
vector<int> val(n);
for(int i=1;i<=n;i++){
val[i-1]=i;
}
vector<bool> select(n,false);
fill_n(select.begin(),k,true);//fill_n(start,count,val)从起始点开始依次赋予count个元素val的值。
do{
vector<int> path;
for(int i=0;i<n;i++){
if(select[i]) path.push_back(val[i]);
}
ans.push_back(path);
}while(prev_permutation(select.begin(),select.end()));//由原排列得到字典序中上一次最近排列
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: