标签:self pos input pen one put out example collect
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]
标签:self pos input pen one put out example collect
原文地址:https://www.cnblogs.com/xuanlu/p/11569694.html