题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
解题思路
把字符串分成两个部分:一部分是选定字符串的第一个字符;另外一部分是第一个字符后面所有字符。拿第一个字符和后面的字符逐个交换。参考回溯法思想:

import java.util.ArrayList;
import java.util.TreeSet;
public class Solution {
/*
public static void main(String[] args) {
Demo pDemo = new Demo();
System.out.println(pDemo.Permutation("ABcdfg").toString());
}
*/
public ArrayList<String> Permutation(String str){
ArrayList<String> result = new ArrayList<String>();
if(str == null || str.length() == 0) return result;
char [] ch = str.toCharArray();
TreeSet<String> temp = new TreeSet<String>();
Permutation(ch , 0 ,temp);
result.addAll(temp);
return result;
}
private void Permutation(char [] ch,int begin ,TreeSet<String> result) {
if (ch == null || ch.length == 0 || begin < 0 || begin > ch.length -1) return ;
if (ch.length - 1 == begin) {
result.add(String.valueOf(ch));
}else {
for (int i = 0; i < ch.length; i++) {
swap(ch, begin, i);
Permutation(ch, begin + 1, result);
swap(ch, begin, i);
}
}
}
private void swap(char[] ch, int a, int b) {
char temp = ch[a];
ch[a] = ch[b];
ch[b] = temp;
}
}