String arrangement (full array)

Disclaimer: This article is written self-study, pointed out that if the error also hope, thank you ^ - ^ https://blog.csdn.net/weixin_43871369/article/details/90523139

Title Description

A method for the preparation of, determining all permutations of a string.

Given a String  A and a int  n- , represents a string and its length, return all permutations of the character string, to ensure the string is equal to 11 and less than the length of the character string are uppercase English characters, a character string arrangement Sort by dictionary order from largest to smallest. (Not merged repeated string)

Test sample:

"ABC"
返回:["CBA","CAB","BCA","BAC","ACB","ABC"]

Solution 1

//标志位法
class Permutation {
public:
    static bool cmp(const string str1,const string str2)
    {
        return str1>str2;
    }
    void permutation(vector<string>&ans,int index,vector<int>flag,string str,string temp)
    {
        temp+=str[index];
        flag[index]=1;
        for(int i=0;i<str.size();++i)
        {
            if(!flag[i])
           permutation(ans,i,flag,str,temp);
        }
        if(temp.size()==str.size()) ans.push_back(temp);
    }
    vector<string> getPermutation(string A) {
        vector<string>res;
        vector<int>state(A.size());
        fill(state.begin(),state.end(),0);
        string ch;
        for(int i=0;i<A.size();++i)
        {
            ch="";
            permutation(res,i,state,A,ch);
        }
        sort(res.begin(),res.end(),cmp);
        return res;
    }
};

Solution 2

//拆分法,可以将abcd拆分为a[bcd]、b[acd]、c[abd]、d[abc],其中[]代表全排列
class Permutation {
public:
    void permutation(string str,vector<string>&ans,int cnt)
    {
        if(cnt==str.size()-1) ans.push_back(str);
        for(int i=cnt;i<str.size();++i)
        {
            swap(str[cnt],str[i]);
            permutation(str,ans,cnt+1);
            swap(str[cnt],str[i]);
        }
    }
    vector<string> getPermutation(string A) {
        vector<string>res;
        if(A.size()<=0) return res;
        permutation(A,res,0);
        sort(res.begin(),res.end(),greater<string>());
        return res;
    }
};

The same algorithm can be applied to an array, see  different ways full array (STL and recursive algorithms) 

Guess you like

Origin blog.csdn.net/weixin_43871369/article/details/90523139