字符串的排列

题目描述

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



提交链接:点击




思路:利用递归思路来解决,先固定一个字母,然后接下来就是其他的字母。首先考虑给定abcd字符串,那么我们可以先将a固定,那么接下来就是
bcd的排列;考虑完以后,可以将a与b进行交换,固定b,那么接下来就是acd排列。
将b与c交换,固定c,那么接下来就是abd的排列;将d与c交换,固定d,那么接下来就是abc的排列;




代码:
class Solution {
public:
    vector<string> result;
    vector<string> Permutation(string str) {
        sort(str.begin(),str.end());
        int len=str.length();
        int index=0;
        Perm(str,0,len);
        return result;
    }
    //返回str中从index位置开始的字符序列
    void Perm(string str, int index, int len){
        if(index==len-1){
            result.push_back(str);
            return;
        }
        for(int i=index;i<len;i++){
            if(i!=index && str[i]==str[index]) continue;
            swap(str[index],str[i]);   //固定一个字符
            Perm(str,index+1,len);     //接下来的就是递归,index+1
        }
    }
};
 
原文地址:https://www.cnblogs.com/logo-88/p/9787619.html