leetcode-77-Combinations
来源:互联网 发布:淘宝淘客联盟 编辑:程序博客网 时间:2024/06/05 23:41
问题
题目:[leetcode-77]
思路
dfs搞定。
由于限定了层数,所以到k层的时候返回即可。
写代码的时候有一个bug,由于事先分配了空间,所有不能用pop_back().
对于全排列如果也指定k位,那么也需要用dfs的办法,之前的办法可能就不可行了。
代码
class Solution {public: vector<vector<int>> combine(int n, int k) { vector<int> nums; vector< vector<int> > ret; map<int, bool> vis; dfs( 0, k, n, nums, vis, ret ); return ret; }private: void dfs( int depth, int k, int n, vector<int>& nums, map<int,bool>& vis, vector<vector<int>>& ret) { if( depth == k ) ret.push_back( nums ); else { for( int x = 1; x <= n; ++x ) { if( vis.find(x) != vis.end() && vis[x] ) continue; if( nums.size() && x <= nums[nums.size()-1] ) continue; nums.push_back(x); vis[x] = true; dfs( depth+1, k, n, nums, vis, ret ); nums.pop_back(); vis[x] = false; } } }};
阅读全文
0 0
- LeetCode 77 Combinations
- [leetcode 77] Combinations
- Leetcode NO.77 Combinations
- [leetcode] 77 Combinations
- [LeetCode 77]Combinations
- leetcode || 77、Combinations
- leetcode-77 Combinations
- LeetCode-77 Combinations(组合)
- Combinations - LeetCode 77
- leetcode 77:Combinations
- LeetCode(77) Combinations
- Leetcode #77 Combinations
- [leetcode-77]Combinations(java)
- leetcode 77: Combinations
- LeetCode(77) Combinations
- 【leetcode】【77】Combinations
- leetcode 77:Combinations
- 【LEETCODE】77-Combinations [Python]
- Prototype(原型模式)
- nc6报错 Failed to load ESAPI.properties as a classloader resource.
- hdu 1896 Stones
- 解决org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
- cordova device插件——获取设备信息
- leetcode-77-Combinations
- 求二叉树叶子节点的个数/求二叉树第k层的节点个数。
- HDOJ 5093 Battle ships 【二分匹配】
- 综合小项目(HTML+JQuery+js+Ajax+mysql+H5)
- html5离线缓存机制--manifest
- Hibernate(一)—环境搭建和基本的增删改查
- 【Django异常】django-admin.py startproject Project只能调出来django-admin.py而不创建项目
- java String.valueOf()的作用
- Cmake编译出错