劍指offer 面試題28:字符串的排列

題目:

輸入一個字符串,按字典序打印出該字符串中字符的所有排列。

例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。

結果請按字母順序輸出。


解題思路:遞歸~~~

分兩步:

第一步:求出所有可能出現在第一個位置的字符,即把第一個字符和後面所有的字符交換;

第二步:固定一個字符,求後面所有字符的排列。此時,遞歸上面的做法。

這裏寫圖片描述

劍指offer給出的代碼:

C語言版本

void Permutation(char* pStr, char* pBegin);

void Permutation(char* pStr)
{
    if(pStr == NULL)
        return;

    Permutation(pStr, pStr);
}

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;
        }
    }
}

class Solution {
public:
    vector<string> Permutation(string str) {
        vector<string> res;
        if (str.empty())
            return res;
        Permutation(res, str, 0);
        sort(res.begin(), res.end());
        return res;
    }

    void Permutation(vector<string> &array, string str, int begin)
    {
        if (begin==str.size()-1)
            array.push_back(str);
        for (auto i = begin; i != str.size(); ++i)
        {
            if (i != begin&&str[i]==str[begin])
                //若有重複元素則跳過
                continue;
            //第一次交換元素
            swap(str[i] , str[begin]);
            Permutation(array, str, begin + 1);
            //恢復元素
            swap(str[i], str[begin]);
        }
    }
};

測試代碼:

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
    sultion test;
    vector<string> res;
    string string1("abca");
    res = test.Permutation(string1);
    for (auto temp : res)
        cout << temp<<endl;


    system("pause");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章