题目:输入一个字符串,打印出该字符串中字符的所有排列。
思路:使用递归来做,
解决方案:
···
public class Question38 {
public static void permutation(char[] str){
if (str == null) return;
permutation(str, 0);
}
private static void permutation(char[] str,int begin){
if (begin == str.length - 1) {
String result = new String(str);
System.out.println(result);
}else {
for (int i=0; i<str.length; i++){
swap(str, begin, i);
permutation(str, begin+1);
swap(str, begin, i);
}
}
}
private static void swap(char[] str, int index1, int index2){
char tmp = str[index1];
str[index1] = str[index2];
str[index2] = tmp;
}
public static void main(String[] args) {
String str = "abc";
char[] arr = str.toCharArray();
permutation(arr);
}
}
···
网友评论