題目:輸入一個(gè)字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串a(chǎn)bc,則打印出由字符a,b,c所能排列出來(lái)的所有字符串a(chǎn)bc,acb,bac,bca,cab和cba。
輸入描述:
輸入一個(gè)字符串,長(zhǎng)度不超過(guò)9(可能有字符重復(fù)),字符只包括大小寫(xiě)字母。
代碼:
import java.util.Collections;
import java.util.ArrayList;
import java.util.HashSet;
public class Solution {
public ArrayList<String> Permutation(String str) {
ArrayList<String> res = new ArrayList<>();
if(str == null || str.length() == 0){
return res;
}
HashSet<String> set = new HashSet<>();
helper(set, str.toCharArray(), 0);
res.addAll(set);
Collections.sort(res);
return res;
}
void helper(HashSet<String> res, char[] chars, int k){
if(k == chars.length){
res.add(new String(chars));
return;
}
for(int i = k; i < chars.length; i++){
swap(chars,i, k);
helper(res, chars, k + 1);
swap(chars,i, k);
}
}
void swap(char[] chars, int i, int j){
if(i != j){
chars[i] ^= chars[j];
chars[j] ^= chars[i];
chars[i] ^= chars[j];
}
}
}