在劍指offer上刷題時遇到的題目:
輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba
輸入一個字符串,長度不超過9(可能有字符重複),字符只包括大小寫字母。
本博客參考:1. https://blog.csdn.net/u012351768/article/details/52760466 2. https://www.jb51.net/article/134412.htm
本題目用到了遞歸思想,算法步驟如下:
(1)固定第一個元素,將剩下的元素進行全排列;(那剩下的元素中又可以分爲第一個和剩下的元素,這樣就用到了遞歸)
(2)每一個字符都要有做第一個元素的機會,即將剩下的元素依次與第一個進行交換;
(3)每次交換後的數據,在進行遞歸處理了之後需要再交換回原來的位置,以便後面的字符與其在進行交換;
(4)在最後的按字典序輸出的處理中,使用到了TreeSet和ArrayList,這兩個容器相互轉換時可以直接使用addAll的方法,其中TreeSet具有排序和唯一性的功能。
代碼如下:
public static ArrayList<String> Permutation(String str) {
char[] data = str.toCharArray();
ArrayList<String> result = new ArrayList<String>();
Permutation(data, 0, result);
//利用TreeSet進行排序和去除重複的元素
TreeSet<String> set = new TreeSet<String>();
set.addAll(result);
result.clear();
result.addAll(set);
return result;
}
/**
* @param data 字符串轉化成的字符數組
* @param beginIndex 起始位置
* @param result 包含所有的字符串的全排列的結果集合
*/
public static void Permutation(char[] data, int beginIndex, ArrayList<String> result) {
//如果已經交換到最後一位,那麼將這個字符串添加進結果集合
if (beginIndex == data.length - 1) {
result.add(new String(data));
} else {
for (int i = beginIndex; i < data.length; i++) {
// 如果第i個元素和開始的元素相同,則兩個元素就不交換
if (i != beginIndex && data[i] == data[beginIndex])
continue;
//交換
char temp = data[beginIndex];
data[beginIndex] = data[i];
data[i] = temp;
//遞歸
Permutation(data, beginIndex + 1, result);
//再換回來
temp = data[beginIndex];
data[beginIndex] = data[i];
data[i] = temp;
}
}
}
}