昨天开始看《数据结构与算法分析_java语言描述》这本书,第一章的习题1.6 让我想了老半天,网上查了下发现解决方法蛮多的,用的都是递归,不禁感慨算法真是太神奇了- -
so 在这里记录一下我找到的几个解决方法。
第一种:
public static List<String> pailie(String str){
List<String> result = new ArrayList<String>();
if(str.length()==1) result.add(str);
else {
char thisChar = str.charAt(0);
List<String> temp = pailie(str.substring(1));
for(int i =0;i<temp.size();i++){
String thisStr = temp.get(i);
for(int j=0 ; j<= thisStr.length() ; j++){
String firstStr = thisStr.substring(0, j);
String lastStr = thisStr.substring(j);
result.add(firstStr + thisChar + lastStr);
}
}
}
return result;
}
public static void main(String[] args) {
List<String> newList = pailie("abcd");
for(String temp : newList){
System.out.println(temp);
}
System.out.println("-----------------------------------");
System.out.println(newList.size());
}
第二种:
public static void main(String[] args) {
String str = "abc";
permutation(str.toCharArray(), 0);
}
public static void permutation(char[] str, int i) {
if (i >= str.length)
return;
if (i == str.length - 1) {
System.out.println(String.valueOf(str));
} else {
for (int j = i; j < str.length; j++) {
char temp = str[j];
str[j] = str[i];
str[i] = temp;
permutation(str, i + 1);
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
}
第三种:
public static int c = 0;
public static void main(String[] args) {
String s = "abcd";
printAllArray(s, "");
}
private static void printAllArray(String s, String n) {
if (s.length() == 0) {
System.out.println(n + " --- " + ++c);
} else {
for (int i = 0; i < s.length(); ++i) {
printAllArray(s.substring(1), n + s.charAt(0));
s = s.substring(1) + s.charAt(0);
}
}
}