题目链接
解题方法:
代码:
import java.util.*;
public class Main {
static char[] chs; //题目的字符串
static boolean[] vis; //访问标记
static char[] ans; //暂存每一个排列
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
chs = str.toCharArray();
ans = new char[chs.length];
vis = new boolean[chs.length];
Arrays.sort(chs); //先排序,方便去重
dfs(0);
}
public static void dfs(int point) {
if (point == chs.length) { //一种排列完成,打印它
String s = "";
for (int i = 0; i < ans.length; i++) s += ans[i];
System.out.println(s);
}
for (int i = 0; i < chs.length; i++) {
if (!vis[i]) { //未被访问
vis[i] = true; //标记
ans[point] = chs[i]; //未访问的数字,赋值给ans[point]
dfs(point + 1); //进入下一层,point+1
vis[i] = false; //回溯,使用之后,取消访问标记
while (i < chs.length - 1 && chs[i] == chs[i + 1]) i++; //去重,相同的跳过
}
}
}
}
网友评论