77. Combinations
来源:互联网 发布:mp3添加歌词软件 编辑:程序博客网 时间:2024/06/06 09:25
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],]
代码及思路:
class Solution {public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; vector<int> temp; helper(res, 1, n, temp, k); return res; } void helper(vector<vector<int>>& res, int begin, int n,vector<int>& temp, int& k){ if(k == 0){ res.push_back(temp); return; } if(begin > n) return ; for(int i = begin; i <= n; i++){ temp.push_back(i); k--; helper(res, i + 1, n, temp, k);//这里一定不是helper(res, begin + 1, n, temp, k); 切记! k++; temp.pop_back(); } } //注意: 还有一种写法: /*void helper(vector<vector<int>>& res, int begin, int n,vector<int>& temp, int k){ if(k == 0){ res.push_back(temp); return; } if(begin > n) return ; for(int i = begin; i <= n; i++){ temp.push_back(i); //k--; helper(res, i + 1, n, temp, k - 1);//这里 k - 1 用的是DFS的方法 ,注意此时 k 是传值。 //k++; temp.pop_back(); } }*/};
0 0
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- 77. Combinations
- MSP430应用技巧6:代码速度的优化
- 辞旧迎新(无关学术)
- Html练习2
- MyBatis学习之代码生成器Generator
- 2017开始学PHP听说PHP是最好的语言
- 77. Combinations
- Android中Intent和IntentFilter进行通信
- JSP脚本中的9个内置对象---08 response对象
- 源码-Oracle数据库管理-第十五章-触发器和游标-Part 4(理解触发器)
- JavaScript事件
- 2016年简直一晃而过
- VS2012+EMGUCV配置与测试
- javaweb/jSP/J2EE图书商城 图书管理源码
- 时间日期滚轮(安卓)