[LC] 46. Permutations
Posted xuanlu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC] 46. Permutations相关的知识,希望对你有一定的参考价值。
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
Time: O(N!)
Space: O(N)
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: res = [] if nums is None or len(nums) == 0: return res my_set = set() cur_list = [] self.dfs(0, my_set, nums, cur_list, res) return res def dfs(self, level, my_set, nums, cur_list, res): if level == len(nums): res.append(list(cur_list)) return for i in range(len(nums)): if nums[i] in my_set: continue my_set.add(nums[i]) cur_list.append(nums[i]) self.dfs(level + 1, my_set, nums, cur_list, res) my_set.remove(nums[i]) cur_list.pop()
Solution 2:
class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] if nums is None or len(nums) == 0: return res self.dfs(nums, 0, res) return res def dfs(self, array, level, res): if level == len(array): res.append(list(array)) return res for i in range(level, len(array)): array[level], array[i] = array[i], array[level] self.dfs(array, level + 1, res) array[i], array[level] = array[level], array[i]
以上是关于[LC] 46. Permutations的主要内容,如果未能解决你的问题,请参考以下文章
[Mdfs] lc90. 子集 II(组合类型枚举+多重背包+去重经典)
如何编译 Informix GLS 语言环境/字符集。 (将 .lc 文件转换为 .lco 以创建数据库的 Informix 语言环境)