字符串的排列

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

输入描述:

输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。


解题思路:
以ABC字符串为例,我们首先固定位置0,交换A与A,A与B,A与C,然后对于交换后的字符串dfs,固定位置1,交换位置1与位置1+1、交换位置1与位置1+2 ... 同时使用set集合过滤
重复的字符串,最后将vector中字符串进行排序。

class Solution {
public:
    set<string> filter;
    vector<string>res;
    void mydfs(string str, int idx){
        if(idx == str.size()){
            return;
        }
        for(int i = idx; i < str.length(); i++){
            string nstr = myswap(str, idx, i);
            if(filter.find(nstr) == filter.end()){
                res.push_back(nstr);
                filter.insert(nstr);
            }
            mydfs(nstr, idx+1);
        }
    }
    vector<string> Permutation(string str) {
        mydfs(str, 0);
        sort(res.begin(), res.end());
        return res;
    }
    string myswap(string str, int idx1, int idx2){
        string newstr = str;
        swap(newstr[idx1], newstr[idx2]);
        return newstr;
    }
};

  

posted @ 2019-04-07 12:07  tcgoshawk  阅读(326)  评论(0编辑  收藏  举报