[C++]LeetCode: 83 Combinations (回溯法)
来源:互联网 发布:最坏的一天 电影 知乎 编辑:程序博客网 时间:2024/05/16 01:40
题目:
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],]
思路:回溯法
构造一个辅助函数,combine_helper.
(1)递归一次,填入一个数字
(2)填入的数字,不能是小于当前数字的值,防止重复
(3)回溯:pop_back()最后加上的一个数字,回溯到上一层
(4)结束条件,当填入的数字达到k个数字时,当前填写完毕,回溯。
关于回溯的具体实现过程,这篇文章有个动画,解释的很生动: Backtracking
Attention:
1. 注意我们填入数字必须是递增的,否则会导致重复数字。
2. 掌握回溯的思想精髓。pop_back很关键。回溯到上一层。
复杂度:非确定性多项式时间复杂性类, NP问题
AC Code:
class Solution {public: vector<vector<int> > combine(int n, int k) { vector<vector<int> > ret; if(n == 0 || k == 0 || n < k) return ret; vector<int> tmp; combine_helper(0, 0, n, k, tmp, ret); return ret; }private: void combine_helper(int start, int num, int n, int k, vector<int> tmp, vector<vector<int> >& ret) { if(num == k) { ret.push_back(tmp); return; } for(int i = start; i < n; i++) { tmp.push_back(i+1); combine_helper(i+1, num+1, n, k, tmp, ret); tmp.pop_back(); } }};
0 0
- [C++]LeetCode: 83 Combinations (回溯法)
- LeetCode-77-Combinations(回溯法)-Medium
- (回溯法)LeetCode#77. Combinations
- [leetcode][回溯] Combinations
- 77.leetcode Combinations(medium)[回溯递归]
- LeetCode 77. Combinations 组合问题C(n,k),树形状态回溯,优化减枝
- 【C++】【LeetCode】77. Combinations
- LeetCode 17. Letter Combinations of a Phone Number 递归回溯法
- LeetCode: Combinations 递归回溯 2种实现方法
- [leetcode][回溯] Letter Combinations of a Phone Number
- leetcode 回溯法 模板
- 回溯法-leetcode
- leetcode 回溯法 模板
- 回溯法-Leetcode转
- 回溯法——combinations同数组的所有组合
- LeetCode: Combinations
- LeetCode: Combinations
- LeetCode Combinations
- [Java]读取文件内容方法总结
- c99在不同编译器的实现情况
- hdu4121 Xiangqi
- HTML5/CSS3hack
- 译Variance Shadow Maps
- [C++]LeetCode: 83 Combinations (回溯法)
- i os 开发者证书 申请 详解
- ORACLE PL/SQL编程之五:异常错误处理
- UiNavigationController的使用
- 数据库系统概论课后习题答案第三章
- IntentService
- firefox 操作技巧
- 东莞怎么找富婆包养
- 案例讲解asp.net中jquery post的用法