LeetCode题解——Combinations
2015-08-26 21:32
281 查看
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:
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] backtracking is very useful. the ieda is similar to combination sumclass Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> ans; vector<int> temp; combine(1,n,k,ans,temp); //call fuction to get combination of k numbers which range is 1-n return ans; } private: void combine(int begin,int n, int k, vector<vector<int>> &ans, vector<int>& temp){ if(k==0){ ans.push_back(temp); return; } //condition : n-i+1 is the range, range must greater than k for(int i=begin;n-i+1>=k;i++){ // for the ith iteration, get the combination of i and k-1 numbers differ from i. temp.push_back(i); combine(i+1,n,k-1,ans,temp);// get the combination of k-1 numbers which range is(i+1,n) temp.pop_back(); } } };
相关文章推荐
- Topcoder SRM666 DIV2第三题,树形DP
- Same Tree
- BZOJ1059: [ZJOI2007]矩阵游戏
- typedef
- 有理想的程序员必须知道的15件事
- Java高手需要注意的25个学习目标
- C#获取QQ旋风的下载记录
- jQuery autocomplete 的例子
- c++中的位运算与逻辑运算
- Runtime类
- Zjnu Stadium
- 2.19 区间重合判定
- Qt浅谈之二十二Qt样式表
- Highcharts+Spring饼图使用实例
- http与https的区别
- caffe 代码大揭秘
- 白发长哪里是肝不好
- GUI
- mysql数据类型整理
- CF 196 Div 2 D (树形dp)