题目链接:https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/
难度:中等

描述:
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。

题解

  1. class Solution:
  2. def permutation(self, s: str) -> List[str]:
  3. chars = list(s)
  4. ret = []
  5. def dfs(x):
  6. if x == len(chars) - 1:
  7. ret.append("".join(chars))
  8. return
  9. char_set = set()
  10. for i in range(x, len(chars)):
  11. if chars[i] in char_set:
  12. continue
  13. char_set.add(chars[i])
  14. chars[x], chars[i] = chars[i], chars[x]
  15. dfs(x+1)
  16. chars[x], chars[i] = chars[i], chars[x]
  17. dfs(0)
  18. return ret