時間限制:C/C++ 1秒,其他語言2秒 空間限制:C/C++ 32M,其他語言64M 熱度指數:633870
題目描述
輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。
輸入描述:
輸入一個字符串,長度不超過9(可能有字符重複),字符只包括大小寫字母。
解答思路:
遇見題目先考慮一下什麼思想,這個有優化子結構,和分治和貪心也不大對的上,所以很有可能是動態規劃。
動態規劃求最優解的時候,採用空間換時間的方法,從每一種可能的最後一步逆推選擇,得到樹狀結構每一條路線每一層的最優解。
這個雖然不是最優解,但是其實記錄的就是每個路線每一層,只不過這個就不需要選擇了,而是全留下。
這個問題同樣是樹狀層次性結構,假如輸入字符串是abc,則具有三層結構。只不過這個是從內到外,最內層是a,從外層是abc的所有排列。不逆推了,順着推。
利用隊列,map,代碼如下:
class Solution {
queue<string>q;
public:
typedef map <string,int> MAP_STD;
vector<string> Permutation(string str) {
vector<string>re;
int len=str.length();
string tmp="0";
if(len==0)return re;
if(len==1){
re.push_back(str);
return re;
}else{
tmp[0]=str[0];
q.push(tmp);;
}
int i=0,j=0,k=0;
int count=1;
for(i=1;i<len;i++){
int c=0;
for(k=0;k<count;k++){
string p=q.front();
q.pop();
int plen=p.length();
tmp=str[i]+p;
q.push(tmp);
c++;
for(j=1;j<p.length();j++){
tmp=p.substr(0,j)+str[i]+p.substr(j);
q.push(tmp);
c++;
}
tmp=p+str[i];
q.push(tmp);
c++;
}
count=c;
}
int size=q.size();
MAP_STD mp;
string word;
for(i=0;i<size;i++){
mp.insert(MAP_STD::value_type(q.front(),0));
q.pop();
}
MAP_STD::iterator tp;
for (tp=mp.begin(); tp!=mp.end();tp++) {
re.push_back(tp->first);
}
return re;
}
};