《劍指offer》字串的排列,《劍指offer》字串

來源:互聯網
上載者:User

《劍指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;};


著作權聲明:本文為博主原創文章,如果轉載,請註明出處

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.