[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:
【思路】
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();
}
}
};
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; } };
相关文章推荐
- 家庭作业 3.57
- 归并排序
- 神经网络数据结构
- synchronized详解。
- SQL存储过程将符合条件的大量记录批量删除脚本
- 家庭作业 3.57
- c/c++指针
- 度量快速开发平台中集成登录CS程序的思路设想
- Add Digits
- IOS开发中enumerateObjectsUsingBlock 函数的用法
- 001.HelloWorld 命令行工程
- C++设计模式(一) 工厂模式
- 黑马程序员——C语言基础---预处理指令
- Java实现字符全阵列阵列
- 二值连通区域检测
- [RFID]IC卡克隆(四)Proxmark3全卡克隆已解密的IC卡
- PLDP2015介绍
- MySQL问题解决:-bash:mysql:command not found
- 软件架构设计模式
- app实现dns解析