leetcode: 46. Permutations
来源:互联网 发布:天猫淘宝优惠卷代理 编辑:程序博客网 时间:2024/06/11 13:05
Q
Given a collection of distinct numbers, return all possible permutations.
Example
For example,[1,2,3] have the following permutations:[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
AC
class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ return self.sub(nums) def sub(self, nums): if len(nums) == 0: return [[]] if len(nums) == 1: return [nums] pattern = self.sub(nums[1:]) c = [] for i in xrange(len(nums)): for p in pattern: c.append(p[:i] + [nums[0]] + p[i:]) return c# Time: O(n * n!)# Space: O(n)class Solution2(object): def permute(self, num): result = [] used = [False] * len(num) self.permuteRecu(result, used, [], num) return result def permuteRecu(self, result, used, cur, num): if len(cur) == len(num): result.append(cur + []) return for i in xrange(len(num)): if not used[i]: used[i] = True cur.append(num[i]) self.permuteRecu(result, used, cur, num) cur.pop() used[i] = Falseif __name__ == "__main__": assert Solution().permute([1, 2, 3]) == [[1, 2, 3], [1, 3, 2], [2, 1, 3], [3, 1, 2], [2, 3, 1], [3, 2, 1]]
阅读全文
0 0
- [LeetCode]46.Permutations
- LeetCode 46.Permutations
- 46. Permutations Leetcode Python
- LeetCode --- 46. Permutations
- [Leetcode] 46. Permutations
- [leetcode] 46.Permutations
- LeetCode 46. Permutations DFS
- 46. Permutations LeetCode
- Leetcode 46. Permutations
- leetcode 46. Permutations
- LeetCode *** 46. Permutations
- LeetCode 46. Permutations
- leetcode 46. Permutations
- LeetCode - 46. Permutations
- 【leetcode】46. Permutations
- leetcode 46. Permutations
- [LeetCode] 46. Permutations
- leetcode 46. Permutations
- 334. Increasing Triplet Subsequence
- Second Minimum Node In a Binary Tree:求二叉树第二小的值
- imageview
- 计算机中的颜色如何表示?
- maven使用antrun运行不同版本的插件
- leetcode: 46. Permutations
- 32-多线程(wait和sleep的区别)1 2 33-多线程(停止线程方式-定义标记) 35-多线程(守护线程-setDaemon).1 2
- 40行JavaScript代码实现的3D旋转魔方动画效果
- 作业
- Cookie与Session机制
- leetcode: 47. Permutations II
- python小问题整合
- clisp 记录:5. 数据和控制流(Data and Control Flow)
- 一文深度揭秘3GPP:2G/3G/4G/Pre-5G标准化制定流程是这样的