面试的时候经常遇到“输入一字符串,输出字符串的所有排列”这道题目,今天我自己实现了一下,用的递归的思路。不多解释,直接上代码吧。
package test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/*
*
* 输入一字符串,输出字符串的所有排列
*/
public class PrintAllSequence {
private static Set set = new HashSet<String>();
private static int len = 5;
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
printAllSeq(list);
System.out.println("共有" + set.size() + "种全排列");
Iterator it = set.iterator();
while(it.hasNext()){
String s = (String) it.next();
System.out.println(s);
}
}
private static List<String> printAllSeq(List<String> list) {
if (list.size() == 1) {
return list;
}
List<String> tempList = new ArrayList<String>();
List<String> resultList = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
String prefix = list.get(i);
list.remove(i);
tempList = printAllSeq(list);
for (int j = 0; j < tempList.size(); j++) {
String result = prefix + tempList.get(j);
if(result.length() == len){
set.add(result);
}
resultList.add(result);
}
list.add(i, prefix);
}
return resultList;
}
}