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

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

tips: 將第一個字符依次與後面的元素交換,遞歸進行

class Solution {
public:
    vector<string> Permutation(string str) {
        vector<string> res;
        if(str=="") {
            return res;
        } else if(str.size()==1) {
            res.push_back(str);
            return res;
        }
        char temp=str[0];
        for (int i = 0; i < str.length(); i++)
        {   
            if(i==0 || str[0]!=str[i]) {
                // 交換i 和 0 處的字符 
                temp=str[0];
                str[0]=str[i];
                str[i]=temp;
                vector<string> str_list = Permutation(str.substr(1,str.length()-1));
                for (int j = 0; j < str_list.size(); j++)
                {
                    string str_one = str[0]+str_list[j];
                    res.push_back(str_one);
                }
                // 換回來
                temp=str[0];
                str[0]=str[i];
                str[i]=temp;
            }
            
        }
        sort(res.begin(),res.end());
        return res;
    }
};
發佈了94 篇原創文章 · 獲贊 10 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章