全排列的代码写过好几个,整理出一个最精简最能理解的版本
import 字符串的排列.Permutation;
import java.util.ArrayList;
import java.util.TreeSet;
public class Solution {
public static void main(String[] args) {
String str = "12345";
ArrayList<String> res = Permutation(str);
return;
}
public static ArrayList<String> Permutation(String str) {
TreeSet<String> set = new TreeSet<>();
if (str.length() != 0){
char[] chars = str.toCharArray();
PermutationHelper(chars, 0, set);
}
ArrayList<String> res = new ArrayList<>();
for (String s : set){
res.add(s);
}
return res;
}
public static void PermutationHelper(char[] chars, int i, TreeSet<String> set){
if (i == chars.length -1){
String s = String.valueOf(chars);
set.add(s);
}
else {
for (int j = i;j<chars.length;j++) {
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
PermutationHelper(chars, i + 1, set);
chars[j] = chars[i];
chars[i] = tmp;
}
}
}
}
有点像深搜,深搜的稍后补上