Leetcode 46. Permutations
https://leetcode.com/problems/permutations/
Medium
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] ]
- 回溯,DFS。注意list作为函数参数时,最后返回结果的写法。
1 class Solution: 2 def permute(self, nums: List[int]) -> List[List[int]]: 3 if not nums: 4 return None 5 6 result = [] 7 used = [False] * len(nums) 8 9 def helper(current, n): 10 if n == 0: 11 result.append(current[:]) # pay attention to [:] 12 return 13 14 for i in range( len( nums ) ): 15 if not used[i]: 16 used[i] = True 17 current.append( nums[i] ) 18 19 helper(current, n - 1) 20 21 current.pop() 22 used[i] = False 23 24 helper([], len(nums)) 25 26 return result