題目描述 [字符串的排列]
輸入一個(gè)字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串a(chǎn)bc,則打印出由字符a,b,c所能排列出來的所有字符串a(chǎn)bc,acb,bac,bca,cab和cba。
輸入描述:
輸入一個(gè)字符串,長度不超過9(可能有字符重復(fù)),字符只包括大小寫字母。
解題思路
- 深度優(yōu)先搜索,當(dāng)序列中的元素不重復(fù)時(shí),存在 n! 種不同的排列;
- 考慮第一個(gè)位置,有 n 種可能
- 當(dāng)選定了第一個(gè)位置,第二個(gè)位置有 n-1 種可能
- 因?yàn)槊看嗡阉鞯臓顟B(tài)數(shù)是遞減的,所以這里的 dfs 是一個(gè)循環(huán)遞歸的過程
代碼
class Solution {
public:
void Permutation(vector<string> &res, string &str, int low, int high) {
if(low==high) res.push_back(str);
for(int i=low;i<=high;i++){
if(i!=low && str[i]==str[low]) continue;
swap(str[i], str[low]);
Permutation(res, str, low+1, high);
swap(str[i], str[low]);
}
}
vector<string> Permutation(string str) {
vector<string> res;
if(str.size()==0) return res;
Permutation(res, str, 0, str.size()-1);
sort(res.begin(), res.end());
return res;
}
};