package algorithm;
/**
* @author zhr_java@163.com
* @date 2022/5/16 13:26
*/
import java.util.*;
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
ArrayList<String> list = solution.Permutation("abc");
list.stream()
.forEach(
x -> {
System.out.println(x);
});
System.out.println(list.size());
}
static Set<String> array = new HashSet<>();
public ArrayList<String> Permutation(String str) {
trasing(str.toCharArray(), 0);
ArrayList<String> list = new ArrayList<>(array);
return list;
}
// 固定第i个,遍历(交换)剩下可能的组合,添加至set中
// HashSet自带去重的特性
//每二层的交换遍历n轮完成之后逐个调换回来,然后会回到上一层遍历的下一轮,然后再次遍历第二层的n轮
void trasing(char[] c, int i) {
array.add(String.valueOf(c));
for (int j = i; j < c.length; j++) {
swap(c, i, j);
trasing(c, i + 1);
swap(c, j, i);//遍历完之后,每层逐个调换回来
}
}
// 交换字符
void swap(char[] t, int x, int y) {
char cr = t[x];
t[x] = t[y];
t[y] = cr;
}
}
关注我的公众号SpaceObj 领取idea系列激活码
![]()