题目 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例
2022-03-06 本文已影响0人
xiaohei_e853
package test;
import java.util.LinkedList;
import java.util.List;
public class PermutaionTest2 {
public static void main(String[] args) {
String input = "ABCD";
List<String> resultList = cal("", input);
System.out.println(resultList);
}
//firt,left
public static List<String> cal(String first, String left) {
List<String> result = new LinkedList<String>();
if (left.length() > 1) {
//递归,得到临时结果
char[] chars = left.toCharArray();
int len = left.length();
for (int i = 0; i < len; i++) {
//把第一位提取出来,剩下的的拼接起来
List<String> s = new LinkedList<String>();
s = cal(String.valueOf(chars[i]), left.substring(0, i).concat(left.substring(i+1, len)));
//对递归结果跟固定为拼接
for (int j = 0; j < s.size(); j++) {
s.set(j,first.concat(s.get(j)));
}
result.addAll(s);
}
return result;
} else {
result.add(first.concat(left));
return result;
}
}
}