[Leetcode]Permutations
来源:互联网 发布:徐州网络推广 编辑:程序博客网 时间:2024/06/16 08:20
Given a collection of numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:
[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
给出一个集合,要求返回它的所有排列~递归解法如下~
class Solution: # @param num, a list of integer # @return a list of lists of integers def permute(self, num): if num is None or len(num) == 0: return [] if len(num) == 1: return [num] res = [] for i in xrange(len(num)): for j in self.permute(num[:i] + num[i+1:]): res.append([num[i]] + j) return res还有一种解法,也是用递归循环处理子问题,维护一个used数组来表示该元素是否已经存在当前结果中,每次取一个元素放入结果,然后递归剩下的元素~
class Solution: # @param num, a list of integer # @return a list of lists of integers def permute(self, num): if num is None or len(num) == 0: return [] self.res = []; used = [False] * len(num) self.helper(num, used, []) return self.res def helper(self, num, used, item): if len(item) == len(num): self.res.append(item) return for i in xrange(len(num)): if not used[i]: used[i] = True self.helper(num, used, item + [num[i]]) used[i] = False
还有非递归解法,可以参考http://blog.csdn.net/linhuanmars/article/details/21569031
0 0
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- LeetCode: Permutations
- LeetCode: Permutations
- [Leetcode] Permutations
- [LeetCode] Permutations
- Leetcode: Permutations
- [Leetcode] Permutations
- [Leetcode] Permutations
- [LeetCode]Permutations
- LeetCode-Permutations
- [leetcode] permutations
- LeetCode - Permutations
- Leetcode: Permutations
- 【leetcode】Permutations
- 【LeetCode】Permutations
- java调色板(用滑块调色)
- USACO3.3.3 Camelot (camelot)
- The JRE could not be found. Edit the server and change the JRE location.
- VS2010 更改MFC标题栏图标和生成的执行文件图标
- 前端进阶学习(三) --css框架初探
- [Leetcode]Permutations
- HTTP消息头中的“Cache-control”控制网页的缓存
- 等级考试(一):三级网络---似曾相识
- centos5.8下php-5.3.2.tar.gz的安装
- USACO3.3.4 Home on the Range (range)
- 工作总结_5
- Intersection of Two Linked Lists
- C++随笔 delete void *
- 黑马程序员——Object C基础——类的声明、创建