70.给出一个函数来输出一个字符串的所有排列(经典字符串问题)。
take abc for example.
f(n) = a + f(n-1);
f(n) = b + f(n-1); arr[0] and arr[1] exchange
f(n) = c + f(n-1); arr[0] and arr[2] exchange
package com.algo.ms;
public class CharPremutation70 {
public void print(char[] arr, int start){
if(start == arr.length -1){
for(int i = 0; i< arr.length ; i++){
System.out.print(arr[i]);
}
System.out.println();
}else {
for(int i = start; i < arr.length; i++){
if(start == i){
this.print(arr, start+1);
}else{
swap(arr, start, i);
this.print(arr, start + 1);
swap(arr, start, i);
}
}
}
}
public void swap(char[] arr, int i, int j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "abcd";
char[] arr = str.toCharArray();
CharPremutation70 charPrem = new CharPremutation70();
charPrem.print(arr, 0);
}
}