码迷,mamicode.com
首页 > 其他好文 > 详细

字符串的排列

时间:2019-04-07 12:47:07      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:title   ati   perm   字符串   sub   超过   for   包括   res   

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串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;
    }
};

  

字符串的排列

标签:title   ati   perm   字符串   sub   超过   for   包括   res   

原文地址:https://www.cnblogs.com/chengsheng/p/10664576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!