LeetCode:Combinations
2016-05-24 11:37
267 查看
Combinations
Total Accepted: 75841 Total
Submissions: 219221 Difficulty: Medium
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:
Subscribe to see which companies asked this question
Hide Tags
Backtracking
Hide Similar Problems
(M) Combination Sum (M)
Permutations
思路:
例:n = 4, k = 3;有combs,comb数组
组合情况有:
1)1 2 3
2)1 2 4
3)1 3 4
4)2 3 4
生成过程:
comb=[], k=3,初始状态;
comb=[1], k=2,加入1;
comb=[1,2], k=1,加入2;
comb=[1,2,3], k=0;加入3,结果添加到combs;
comb=[1,2], k=1;去掉3
comb=[1,2,4], k=0;加入3,结果添加到combs;
comb=[1,2], k=1,去掉4;
comb=[1], k=2,这时由于已经遍历到4(==n),要再去掉2;
comb=[1,3], k=1,加入3;
comb=[1,3,4], k=0,加入4,结果添加到combs;
comb=[1,3], k=1,去掉4;
comb=[1], k=2,这时由于已经遍历到n(==4),要再去掉3;
comb=[1,4], k=1,加入4;已经到n;
comb=[1], k=2,去掉4;
comb=[], k=3,去掉1;
comb=[2], k=2,加入2;
comb=[2,3], k=1,加入3;
comb=[2,3,4], k=0,加入4,结果添加到combs;
c++ code:
Total Accepted: 75841 Total
Submissions: 219221 Difficulty: Medium
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
Hide Tags
Backtracking
Hide Similar Problems
(M) Combination Sum (M)
Permutations
思路:
例:n = 4, k = 3;有combs,comb数组
组合情况有:
1)1 2 3
2)1 2 4
3)1 3 4
4)2 3 4
生成过程:
comb=[], k=3,初始状态;
comb=[1], k=2,加入1;
comb=[1,2], k=1,加入2;
comb=[1,2,3], k=0;加入3,结果添加到combs;
comb=[1,2], k=1;去掉3
comb=[1,2,4], k=0;加入3,结果添加到combs;
comb=[1,2], k=1,去掉4;
comb=[1], k=2,这时由于已经遍历到4(==n),要再去掉2;
comb=[1,3], k=1,加入3;
comb=[1,3,4], k=0,加入4,结果添加到combs;
comb=[1,3], k=1,去掉4;
comb=[1], k=2,这时由于已经遍历到n(==4),要再去掉3;
comb=[1,4], k=1,加入4;已经到n;
comb=[1], k=2,去掉4;
comb=[], k=3,去掉1;
comb=[2], k=2,加入2;
comb=[2,3], k=1,加入3;
comb=[2,3,4], k=0,加入4,结果添加到combs;
c++ code:
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> combs; vector<int> comb; combine(combs,comb,1,n,k); return combs; } void combine(vector<vector<int>> &combs, vector<int> &comb,int begin,int n,int k) { if(k==0){ combs.push_back(comb); return; } for(int i=begin;i<=n;i++) { comb.push_back(i); combine(combs,comb,i+1,n,k-1); comb.pop_back(); } } };
相关文章推荐
- ceph存储 ceph中pglog处理流程
- mybatis学习笔记(七)增删改查
- [leetcode] 350. Intersection of Two Arrays II
- Activity和Service的生命周期(图)
- cygwin 安装以及配置
- 欢迎使用CSDN-markdown编辑器
- 汉字转全拼
- Google I/O 2016 RecyclerView的前世今生,原理详解等
- eclipse配置external tool configurations外部工具
- (HDU 1010) Tempter of the Bone
- Visio画好的图在word中只显示一部分
- 百度地图坐标系和火星坐标系之间的互相转换
- java调用windows的wmi获取设备性能数据
- WebView的分析与使用
- liblinphone注册状态的变化
- LeetCode 350:Intersection of Two Arrays II
- 【前端】优酷、酷6、土豆网视频自动播放代码
- web前端开发命名规则
- RegOpenKeyEx调用失败返回5
- MySQL慢查询