【牛客網】字符串的排列

  • 題目:

題目描述
輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。 結果請按字母順序輸出。
輸入描述:
輸入一個字符串,長度不超過9(可能有字符重複),字符只包括大小寫字母。

  • 《劍指Offer》上代碼
void Permutation(char* pStr, char* pBegin){
    if (*pBegin == '\0'){
        printf("%s\n", pStr);
    }
    else{
        for (char* pCh = pBegin; *pCh != '\0'; ++pCh){
            char temp = *pCh;
            *pCh = *pBegin;
            *pBegin = temp;
            Permutation(pStr, pBegin + 1);
            temp = *pCh;
            *pCh = *pBegin;
            *pBegin = temp;
        }
    }
}
void Permutation(char* pStr){
    if (pStr == NULL)
        return;
    Permutation(pStr, pStr);
}
  • 牛客網AC代碼:
class Solution {
public:
    vector<string> Permutation(string str) {
        if (str == "")
           return result;
        Permutation(str,0);
        sort(result.begin(),result.end());
        auto it = unique(result.begin(),result.end());
        result.erase(it,result.end());
        return result;
    }
    void Permutation(string str,int begin)
        {
        if (begin == str.length())
            {
            result.push_back(str);
        }
        for (int i = begin;i < str.length();i++)
            {
            swap(str[begin],str[i]);
            Permutation(str,begin + 1);
            swap(str[begin],str[i]);
         }
    }

    private:
    vector<string> result;
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章