面试的时候一道编程题,12234所有的不同排列方式,回来才考虑用递归这么做
package com.su.reflect;
import java.util.Set;
/**
*
* @author su
*/
public class NewClass {
public static void main(String args[]) {
String str = "12234";
char[] strArray = str.toCharArray();
Set set = new HashSet();
permute(strArray, 0, strArray.length - 1,set);
}
void permute(char[] list, int low, int high, Set set) {
int i;
if (low == high) {
String cout = "";
for (i = 0; i <= high; i++) {
cout += list[i];
}
if (set.add(cout)) {
System.out.println(cout);
}
} else {
for (i = low; i <= high; i++) {
char temp = list[low];
list[low] = list[i];
list[i] = temp;
permute(list, low + 1, high, set);
temp = list[low];
list[low] = list[i];
list[i] = temp;
}
}
}
}
package com.su.reflect;
import java.util.Set;
/**
*
* @author su
*/
public class NewClass {
public static void main(String args[]) {
String str = "12234";
char[] strArray = str.toCharArray();
Set set = new HashSet();
permute(strArray, 0, strArray.length - 1,set);
}
void permute(char[] list, int low, int high, Set set) {
int i;
if (low == high) {
String cout = "";
for (i = 0; i <= high; i++) {
cout += list[i];
}
if (set.add(cout)) {
System.out.println(cout);
}
} else {
for (i = low; i <= high; i++) {
char temp = list[low];
list[low] = list[i];
list[i] = temp;
permute(list, low + 1, high, set);
temp = list[low];
list[low] = list[i];
list[i] = temp;
}
}
}
}