八皇后问题
static void f(int[] array,int k){
if(k==8){
show(array);
return;
}
for (int i=0;i<8;i++){
array[k]=i;
if(check(array,k,i)){
f(array,k+1);
}
}
}
private static void show(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
System.out.println();
}
private static boolean check(int[] array, int row, int cal) {
for (int i = 0; i < row; i++) {
if(array[i]-cal==0){
return false;
}
if(row-i==Math.abs(array[i]-cal)){
return false;
}
}
return true;
}
回溯求解字符串排序问题
static ArrayList<String> handle(String str){
ArrayList<String> strings = new ArrayList<>();
if(str.length()==0){
return strings;
}
if(str.length()>9){
return strings;
}
if(str.length()==1){
strings.add(str);
return strings;
}
char[] chars = str.toCharArray();
find(strings,chars,0);
Collections.sort(strings);
return strings;
}
private static void find(ArrayList<String> strings, char[] chars, int i) {
if(i==chars.length){
return;
}
if(!strings.contains(String.valueOf(chars))){
strings.add(String.valueOf(chars));
}
for (int j = 0; j < chars.length; j++) {
if(chars[i]!=chars[j]){
swap(chars,i,j);
if(!strings.contains(String.valueOf(chars))){
strings.add(String.valueOf(chars));
}
find(strings,chars,i+1);
swap(chars,i,j);
}else if(!strings.contains(String.valueOf(chars))){
strings.add(String.valueOf(chars));
}
}
}
private static void swap(char[] chars,int i,int j){
char tmp=chars[i];
chars[i]=chars[j];
chars[j]=tmp;
}