• 字符串的排列


    题目描述

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

      

  • 相关阅读:
    spring(1)
    mybatis(7)自定义结果集(一对多/多对一)
    延迟加载
    《构建之法》阅读笔记03
    http socket
    转换
    .net后台通过xmlhttp 和远程服务通讯
    XMLHttpRequest介绍
    js 贪吃蛇
    触发器
  • 原文地址:https://www.cnblogs.com/chengsheng/p/10664576.html
Copyright © 2020-2023  润新知