题目
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
分析
思路一:
代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class Solution {
public ArrayList<String> Permutation(String str) {
char[] chs = str.toCharArray();
ArrayList<String> list = new ArrayList<>();
if(str == null || str.length() == 0) return list;
process(chs, 0, list);
Collections.sort(list);
return list;
}
//递归
public void process(char[] chs, int index, ArrayList<String> list) {
if(index == chs.length - 1) {
list.add(String.valueOf(chs));
}
HashSet<Character> set = new HashSet<>();
for(int i = index; i < chs.length; i++) {
if(!set.contains(chs[i])) {
set.add(chs[i]);
swap(chs, i, index);
process(chs, index + 1, list);
swap(chs, i, index);
}
}
}
//swap
public void swap(char[] chs, int i, int j) {
char tmp = chs[i];
chs[i] = chs[j];
chs[j] = tmp;
}
}