[LeetCode] Combinations
2015-06-16 23:45
375 查看
A typical backtracking problem. For any backtracking problem, you need to be think about three ascepts:
What is a partial solution and when is it finished? --- In this problem, the partial solution is a combination (sol). It is finished once it contains k elements.
How to find all the partial solutions? --- In the following code, I simply traverse all the possible starting elements (start).
When to make recursive calls? --- In the following code, once an element is added to the partial solution, we call the function to generate the remaining elements recursively.
Of course, remember to recover to the previous status once a partial solution is done. In the following code, line 18 (sol.pop_back()) is for this purpose.
The following should be self-explanatory :)
What is a partial solution and when is it finished? --- In this problem, the partial solution is a combination (sol). It is finished once it contains k elements.
How to find all the partial solutions? --- In the following code, I simply traverse all the possible starting elements (start).
When to make recursive calls? --- In the following code, once an element is added to the partial solution, we call the function to generate the remaining elements recursively.
Of course, remember to recover to the previous status once a partial solution is done. In the following code, line 18 (sol.pop_back()) is for this purpose.
The following should be self-explanatory :)
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int> > res; vector<int> sol; combination(1, n, k, sol, res); return res; } private: void combination(int start, int n, int k, vector<int>& sol, vector<vector<int> >& res) { if (k == 0) { res.push_back(sol); return; } for (int i = start; i <= n; i++) { sol.push_back(i); combination(i + 1, n, k - 1, sol, res); sol.pop_back(); } } };
相关文章推荐
- Map集合使用
- JSP deleteCategory.jsp (line: 9, column: 67) The JSP specification requires that an attribute name i
- Plus One
- php Hash函数了解
- vim方向键乱码
- 2015最流行的android组件、工具、框架大全
- javascript 获取调用属性的对象
- NodeJS框架express的途径映射(路由)功能及控制
- CentOS下如何完全卸载MySQL?解决卸载不干净的问题
- Android中如何查看内存
- 问题安装完hadoop后无法连接dfs
- Andriod网络优化相关技术点整理
- CentOS 7 之Helloworld with c
- ORA-01123:无法启动联机备份;未启用介质恢复.
- Struts2入门2
- Maven + Nexus + SVN + Eclipse 配置步骤说明
- Sokcet编程常用函数
- Android中AsyncTask的分析和使用
- UIButton的一些基本用法
- LeetCode——Contains Duplicate II