whole_arrang.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from typing import List
  2. class Solution:
  3. def permute(self, nums: List[int]) -> List[List[int]]:
  4. def dfs(nums, size, depth, path, used, res):
  5. if depth == size:
  6. res.append(path[:])
  7. return
  8. for i in range(size):
  9. # used[i] 为 false时
  10. if not used[i]:
  11. used[i] = True
  12. path.append(nums[i])
  13. def dfs(nums, size, depth, path, used, res):
  14. if depth == size:
  15. res.append(path[:])
  16. return
  17. for i in range(size):
  18. # used[i] 为 false时
  19. if not used[i]:
  20. used[i] = True
  21. path.append(nums[i])
  22. dfs(nums, size, depth + 1, path, used, res)
  23. used[i] = False
  24. path.pop()
  25. used[i] = False
  26. path.pop()
  27. size = len(nums)
  28. if len(nums) == 0:
  29. return []
  30. # 一维数组赋值
  31. used = [False for _ in range(size)]
  32. # 二维数组赋值
  33. # [[False for _ in range(size)] for _ in range(size)]
  34. res = []
  35. dfs(nums, size, 0, [], used, res)
  36. return res
  37. if __name__ == '__main__':
  38. nums = [1, 2, 3]
  39. solution = Solution()
  40. res = solution.permute(nums)
  41. print(res)