利用哈希表
class Solution:def permute(self, nums: List[int]) -> List[List[int]]:ans = []path = []n = len(nums)def dfs(i, s):if i==n:ans.append(path[:])returnfor x in s:path.append(x)dfs(i+1, s-{x})path.pop()dfs(0, set(nums))return ans
利用访问数组
class Solution:def permute(self, nums: List[int]) -> List[List[int]]:ans = []path = []n = len(nums)on_path = [False]*ndef dfs(i):if i==n:ans.append(path[:])returnfor j in range(n):if not on_path[j]:path.append(nums[j])on_path[j] = Truedfs(i+1)on_path[j] = Falsepath.pop()dfs(0)return ans
直接将nums[i] 的元素超出题目设置范围
class Solution:def permute(self, nums: List[int]) -> List[List[int]]:ans = []path = []n = len(nums)def dfs(i):if i==n:ans.append(path[:])returnfor j in range(n):if nums[j] <=10 :path.append(nums[j])nums[j]+=100dfs(i+1)nums[j]-=100path.pop()dfs(0)return ans