leetcode -- Combination -- 重点,求可能的0,1全排列
2015-12-13 21:19
309 查看
https://leetcode.com/problems/combinations/
这题是经典的back tracking的题目。只要求出0,1全排列就行。利用backtracking的模板
这里的m是表示第m个元素
这里的start是表示第start个元素
pos表示现在的level
还有其他解法参考:
没有太理解。再看看
/article/4982550.html
https://www.zybuluo.com/chanvee/note/61530
http://oldoldb.com/MyCodeForLeetCode/2014/07/28/Combinations/
/article/2219404.html
关于backtracking:
/article/4935263.html
思路1: 枚举0,1全排列。
这里的dfs tree: 见自己总结的notes这题是经典的back tracking的题目。只要求出0,1全排列就行。利用backtracking的模板
这里的m是表示第m个元素
class Solution(object): def dfs(self, m, k, nums, subres, res): if sum(subres) == k: res.append([nums[i] for i,c in enumerate(subres) if c == 1]) return elif m >= len(nums): return else: subres[m] = 0 self.dfs(m+1, k, nums, subres, res) subres[m] = 1 self.dfs(m+1, k, nums, subres, res) def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ nums = [x + 1 for x in xrange(n)] subres = [0]*n res = [] self.dfs(0, k, nums, subres,res) return res
思路2:另一种组合树
这里的dfs tree: 见自己总结的notes。 每个节点就是A数组的一个元素A[k],子节点(possible candidates)就是A[j], j>k这里的start是表示第start个元素
pos表示现在的level
class Solution: def dfs(self,pos,k,n,start,ans,vec): if pos==k: temp=vec[:] ans.append(temp) return for i in range(start,n+1): vec[pos]=i self.dfs(pos+1,k,n,i+1,ans,vec) # @return a list of lists of integers def combine(self, n, k): ans=[] vec=[0 for i in range(k)] self.dfs(0,k,n,1,ans,vec) return ans
还有其他解法参考:
没有太理解。再看看
/article/4982550.html
https://www.zybuluo.com/chanvee/note/61530
http://oldoldb.com/MyCodeForLeetCode/2014/07/28/Combinations/
/article/2219404.html
关于backtracking:
/article/4935263.html
自己重写code
class Solution(object): def dfs(self, depth, candidates, start, end, k, subres, res): if depth == k: res.append(subres) i = start while i < end: self.dfs(depth + 1, candidates, i + 1, end, k, subres + [candidates[i]], res) i += 1 def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ nums = [i + 1 for i in xrange(n)] res = [] self.dfs(0, nums, 0, n, k, [], res) return res
相关文章推荐
- [CV] bundler安装
- XSS quiz 6~10解题方案
- Ubuntu下安装matlab应用程序图文教程(详细 全面)
- C#——类和继承
- 杭电Red and Black。。。。水题
- vmware中的3种网络模式:桥接、NAT(地址转换)、host-only
- 二叉排序树
- 创建SSH Key连接github或gitlab
- android:gravity 和 android:layout_gravity 区别
- 创建SSH Key连接github或gitlab
- c语言总结
- 文字检测
- nova http 409 虚拟机状态重置
- [javase学习笔记]-4.4 函数的重载
- 申请内存的函数有哪些
- Q:应用程序无法正常启动(0xc000007b)
- 使用Windows Live发布博客到博客园
- 操作系统---基础题目汇总十三
- TCP/IP详解卷1 读书笔记:第二十八章 SMTP和POP3协议
- vmalloc 实现