Full array [] string recursively

The general idea:

In fact, not been well understood until the whole arrangement until you see an interesting explanation.

The whole arrangement is recursive, in order recursive design, analyze only "present": For the first character, we have two options: The first is to go to this character into the mix (each location can be put, so traverse position, and after each element are exchanged); the second is do not put this character into the mix to go (in fact, and the exchange itself).

Similarly, each character is after this operation. Recursive. Critical conditions are: the current for this character to the last, so this time the string can be used as a possible result string.

Precautions: switching function for character strings, remember parameter "reference" type , as to substantially change the string; was added to the resulting string vector storage, such as to avoid a plurality of "aa" memory (no location but in fact the same as the content), is to use find (look for the starting address, ending address lookup, what to look for) == finds the end of the string to determine the address does not exist before .

AC Code:

class Solution {
public:
    vector<string> res;
    vector<string> Permutation(string str) {
        if(str.size()==0)
            return res;
        if(str.size()==1)
        {
            res.push_back(str);
            return res;
        }
        QuanPaiLie(str,0);
        
        //牛客网判题要求按字典序顺序输出
        sort(res.begin(),res.end());
        
        return res;
    }
    
    void QuanPaiLie(string &str,int begin) //这个str也应该传引用,因为递归过程中要有承接关系,而不是重新创副本
    {
        if(begin==str.size()-1)   //不需要递归了
        {
            //注意这个判重很容易忽略,不然容易出现多个aa
            if(find(res.begin(),res.end(),str) == res.end()) //find从begin搜到end说明搜到最后了都没有
            {
                res.push_back(str);
                return ;
            }
        }
        else //还需要递归
        {
            for(int i=begin;i<=str.size()-1;i++)
            {
                swapChar(str,begin,i);
                QuanPaiLie(str,begin+1);
                swapChar(str,begin,i); //记得换回来!!!
            }
        }
    }
    
    void swapChar(string &str,int a,int b) //加引用哟,因为要实质性改变
    {
        char temp=str[a];
        str[a] = str[b];
        str[b] = temp;
    }
};

 

Guess you like

Origin blog.csdn.net/m0_38033475/article/details/91997802