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