troubleasy

导航

 
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。(输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。)
思路:

 

字符串长度为n,

第二行,固定第一位,第一位元素与n位元素交换。有n个可能;

第三行,固定前两位,第二位元素与n-1位元素交换,上一层每个节点在第三层有n-1个可能;

...

第n行,固定前n-1位,第n-1位元素与两位元素交换。

     void swap(string &str,int i,int j)
        {
            char c;
            c=str[i];
            str[i]=str[j];
            str[j]=c;
        }
    vector<string> Permutation(string str) {
        vector<string> res;
        int begin=0;
        Permutation(str,begin,res);
        return res;
    }
    void Permutation(string str,int begin,vector<string>& res)
    {
        if(begin==str.size()-1)
        {
            res.push_back(str);
        }
        else{
             for(int i=begin;i<str.size();i++)
             {
                 if(begin!=i&&str[begin]==str[i])
                 {
                     continue;//重复元素跳过
                 }   
                 swap(str,begin,i);
                 Permutation(str,begin+1,res);       
             }
        }
    }
posted on 2020-05-27 00:12  troubleasy  阅读(103)  评论(0编辑  收藏  举报