1. 题目
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
2. 示例
输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]
3. Code
3.1 回溯+交换
1 public class PermutationB {
2 public String[] permutation(String s) {
3 HashSet<String> ans = new HashSet<>();
4 char[] str = s.toCharArray();
5 perm(str, 0, s.length() - 1, ans);
6 return ans.toArray(new String[ans.size()]);
7 }
8 public static void perm(char[] str, int start, int end, HashSet<String> ans) {
9 /**
10 * @Method: perm
11 * @Author: haifwu
12 * @Version: 1.0
13 * @Date: 21/05/2021 15:50
14 * @param str
15 * @param start
16 * @param end
17 * @param ans
18 * @Return: void
19 * @Description: 回溯 +交换
20 */
21 if(start == end) {
22 StringBuffer sb = new StringBuffer();
23 for (char s : str) {
24 sb.append(s);
25 }
26 ans.add(sb.toString()); // 添加排序方案
27 } else {
28 for(int i = start; i <= end; i++) {
29 swap(str, start, i); // 交换,将i固定到第x位
30 perm(str, start + 1, end, ans); // 开启固定第x+1位字符
31 swap(str, start, i); // 恢复交换
32 }
33 }
34 }
35
36 public static void swap(char[] array,int i,int j) {
37 char temp = array[i];
38 array[i] = array[j];
39 array[j] = temp;
40 }
41
42 public static void main(String[] args) {
43 String s = "abcd";
44 for(String str : new PermutationB().permutation(s)) {
45 System.out.println(str);
46 }
47 }
48 }