fork download
  1.  
  2. ### https stackoverflow.com/questions/76577865/
  3. ### understanding-the-for-loop-in-python-permutation-
  4. ### algorithm-back-tracking
  5.  
  6. class Solution:
  7. def permute(self, nums: list[int]) -> list[list[int]]:
  8. res = []
  9.  
  10. def backtrack(path, visited):
  11. if len(path) == len(nums):
  12. res.append(path)
  13. return
  14.  
  15. for i in range(len(nums)):
  16. if not visited[i]:
  17. visited[i] = True
  18. backtrack(path + [nums[i]], visited)
  19. visited[i] = False
  20.  
  21. backtrack([], [False] * len(nums))
  22. return res
  23.  
  24. print(Solution().permute(nums=[1, 2, 3]))
  25.  
  26. ## [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1],
  27. ## [3, 1, 2], [3, 2, 1]]
  28.  
  29.  
Success #stdin #stdout 0.04s 9668KB
stdin
Standard input is empty
stdout
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]