题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
import java.util.ArrayList;
import java.util.*;
public class Solution {
public ArrayList<String> Permutation(String str) {
ArrayList<String> res = new ArrayList<>();
if(str==null || str.length()==0) return res;
permutation(str.toCharArray(),0,res);
Collections.sort(res);
return res;
}
public void permutation(char[] chs,int i,ArrayList<String> res){
if(i==chs.length-1){
String s = String.valueOf(chs);
if(!res.contains(s))
res.add(s);
return;
}
for(int j=i;j<chs.length;j++){
swap(chs,i,j);
permutation(chs,i+1,res);
swap(chs,i,j);
}
}
public void swap(char[] chs,int i,int j){
char temp = chs[i];
chs[i] = chs[j];
chs[j] = temp;
}
}