Niuke.com's sword refers to Offer - the arrangement of strings

Topic description

Enter a string and print out all permutations of the characters in the string lexicographically. For example, if the string abc is input, all strings abc, acb, bac, bca, cab and cba that can be arranged by the characters a, b, and c are printed out.

Enter description:

Enter a string with a length of no more than 9 (there may be repeated characters), and the characters only include upper and lower case letters.

NOTE: The final output is to print out all permutations of the characters in the string in lexicographical order

Problem solving ideas

To find the full permutation of the entire string, you can do it in two steps:

  1.  Find the characters that may appear in the first position, that is, exchange the first character with all the following characters;
  2.  In the case of fixing the first character, find the full arrangement of all the following characters.

Obviously, the above process can be done recursively.

Points to note:

  • When looking for the characters that may appear in the first position, you need to exchange the first character with all the following characters. The first exchange should be the exchange of itself and itself to ensure that there is no shortage of strings;
  • It is necessary to pay attention to the situation that repeated characters (such as "aa") may appear in the string str. If the characters are repeated, there is no need to exchange them to avoid two identical strings appearing in the final output;
  • The output required by the final title is: print out all permutations of the characters in the string in lexicographic order , so a sorting is required.

code

class Solution {
public:
    vector<string> Permutation(string str) {
        if( str.size() == 0 )
            return res;
        help( str, 0 );
        sort(res.begin(),res.end());
        return res;
    }
    vector<string> res;
    void help( string str, int index )
    {
        if( index == str.size()-1 )
        {
            res.push_back( str );
            return;
        }
        for( int i=index;i<str.size();i++ ) //The first exchange should be the exchange of itself and itself, so it starts from i=index, because str[index] can also be used as a starting character of
        {
            if( str[index] == str[i] && index != i ) //It is necessary to pay attention to the situation that repeated characters (such as "aa") may appear in the string str. If the characters are repeated, you can skip the process to avoid Two identical strings appear in the final output
                continue;
            swap( str[index], str[i] );
            help( str, index+1 );
            swap( str[index], str[i] );
        }
        return;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325702724&siteId=291194637