《劍指offer》字串的排列,《劍指offer》字串
【 聲明:著作權,轉載請標明出處,請勿用於商業用途。 聯絡信箱:libin493073668@sina.com】
題目連結:http://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7?rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
題目描述
輸入一個字串,按字典序列印出該字串中字元的所有排列。例如輸入字串abc,則列印出由字元a,b,c所能排列出來的所有字串abc,acb,bac,bca,cab和cba。 結果請按字母順序輸出。
輸入描述:
輸入一個字串,長度不超過9(可能有字元重複),字元只包括大小寫字母。
思路:
題意說的很清楚,就是求這個字串的全排列,我們知道在標準庫裡面有一個很方便的函數可以求全排列。
但是面試官的本意肯定不會是想考我們會不會這個函數,而是想看看我們怎麼親手來實現,所以我們還有必要學會遞迴的寫法。
但是遞迴的結果我們要注意排序和去重。
1.使用函數
class Solution{ public: vector<string> Permutation(string str) { vector<string> ans; if(str=="") return ans; sort(str.begin(),str.end()); do { ans.push_back(str); } while(next_permutation(str.begin(),str.end())); return ans; }};
2.遞迴
class Solution{public:vector<string> Permutation(string str){if(str=="")return ans;Solve(str,0);sort(ans.begin(),ans.end());auto it = unique(ans.begin(),ans.end());ans.erase(it,ans.end());return ans;}void Solve(string str,int beg){if(beg==str.length()){ans.push_back(str);return ;}for(int i = beg; i<str.length(); i++){swap(str[beg],str[i]);Solve(str,beg+1);swap(str[beg],str[i]);}}private:vector<string> ans;};
著作權聲明:本文為博主原創文章,如果轉載,請註明出處