] [Prove safety arrangement offer38 string

If this is not lexicographic ordering, the direct use of recursive thinking, the arrangement of the string as two steps, the first step, the exchange and the first letter of any one letter (including their own, but no other letters and their equivalent ) fixed to the first letter, the first letter is fixed, then string behind such an operation is also employed; however, this does not necessarily sorted according to the lexicographic order;

class Solution {
public:
    vector<string> Permutation(string str) {
        if(str.size()==0) return {};
        sort(str.begin(),str.end());
        vector<string> res;
        per(str,0,res);
        return res;
    }
    void per(string &str,int id,vector<string> &res){
        if(id>=str.size()){
            res.push_back(str);
        }else{
            for(int i=id;i<str.size();i++){
                if(i!=id && str[i]==str[id])continue;
                char tmp=str[id];
                str[id]=str[i];
                str[i]=tmp;
                per(str,id+1,res);
                tmp=str[id];
                str[id]=str[i];
                str[i]=tmp;
            }
        }
    }
};

 

Guess you like

Origin www.cnblogs.com/joelwang/p/11546570.html