題目:
無重復字符串的排列組合。編寫一種方法,計算某字符串的所有排列組合,字符串每個字符均不相同。
示例1:
輸入:S = "qwe"
輸出:["qwe", "qew", "wqe", "weq", "ewq", "eqw"]
示例2:
輸入:S = "ab"
輸出:["ab", "ba"]
提示:
字符都是英文字母。
字符串長度在[1, 9]之間。
分析:
遍歷字符串中每一個字符,將其插入到已生成的字符串,例如qwe,先生成q,然后遍歷到w時,插入到q中,得到qw和wq,再遍歷到e時,插入到qw和wq中得eqw,qew,qwe和ewq,weq,wqe。
再補充一個通過交換字符產生排列的方法。
程序:
class Solution { public String[] permutation(String S) { Queue<String> queue = new LinkedList<>(); for(char ch:S.toCharArray()){ if(queue.isEmpty()){ queue.offer(String.valueOf(ch)); }else{ int len = queue.size(); for(int i = 0; i < len; ++i){ StringBuilder str = new StringBuilder(queue.poll()); for(int j = 0; j <= str.length(); ++j){ StringBuilder strNew = new StringBuilder(str); strNew.insert(j, ch); queue.offer(strNew.toString()); } } } } return queue.toArray(new String[0]); } }
class Solution { public String[] permutation(String S) { char[] chArray = S.toCharArray(); List<String> res = new ArrayList<>(); permutation(res, 0, chArray); return res.toArray(new String[0]); } private void permutation(List<String> res, int index, char[] chArray){ if(index == chArray.length-1){ res.add(new String(chArray)); return; } for(int i = index; i < chArray.length; ++i){ swap(index , i, chArray); permutation(res, index + 1, chArray); swap(index, i, chArray); } } private void swap(int i, int j, char[] chArray){ char ch = chArray[i]; chArray[i] = chArray[j]; chArray[j] = ch; } }