您的位置:首页 > 职场人生

微软面试100题-70

2016-05-14 23:00 549 查看

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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: