permute.py 627 B

123456789101112131415161718192021222324
  1. # Compute all permutations of a string
  2. def permute(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: List[List[int]]
  6. """
  7. def insert_at_i(l, c, i ):
  8. """insert char c at location i of list l."""
  9. sub_start = l[:i]
  10. sub_end = l[i:]
  11. return sub_start + [c] + sub_end
  12. def rec_per(char):
  13. if len(nums) == 0:
  14. return [[char]]
  15. prev = rec_per(nums.pop())
  16. ans = []
  17. for i_l in prev:
  18. for i in range(len(i_l)+1):
  19. ans.append(insert_at_i(i_l,char,i))
  20. print(ans)
  21. return ans
  22. return rec_per(nums.pop())