利用哈希表
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[:]) return for 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]*n def dfs(i): if i==n: ans.append(path[:]) return for j in range(n): if not on_path[j]: path.append(nums[j]) on_path[j] = True dfs(i+1) on_path[j] = False path.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[:]) return for j in range(n): if nums[j] <=10 : path.append(nums[j]) nums[j]+=100 dfs(i+1) nums[j]-=100 path.pop() dfs(0) return ans
标签:排列,nums,int,回溯,List,dfs,ans,path From: https://www.cnblogs.com/r1-12king/p/18305180