一、题目内容

image.png

二、题解

解法1:

思路

深度优先+剪枝
image.png

代码

  1. class Solution {
  2. List<String> ans = new LinkedList<>();
  3. char c[];
  4. public String[] permutation(String s) {
  5. c = s.toCharArray();
  6. recur(0);
  7. return ans.toArray(new String[ans.size()]);
  8. }
  9. public void recur(int x) {
  10. if (x == c.length - 1) {
  11. //新方案
  12. ans.add(String.valueOf(c));
  13. return;
  14. }
  15. HashSet<Character> set = new HashSet<>();
  16. for (int i = x; i < c.length; i++) {
  17. if (set.contains(c[i])) {
  18. continue;
  19. }
  20. set.add(c[i]);//新的固定值
  21. swap(i, x);
  22. recur(x + 1);
  23. swap(i, x);
  24. }
  25. }
  26. private void swap(int i, int x) {
  27. char temp = c[i];
  28. c[i] = c[x];
  29. c[x] = temp;
  30. }
  31. }