Write a method to compute all permutations of a string.
Translate: write a code to calculate all the permutation of a stringAlgorithm.
[Method 1] Recursive Method
First, the string is divided into a [,..., N-2] And a [n-1,
Then recursively solve all the permutation of a [,..., N-2,
Finally insert a [n-1] into all the arrays of a [,..., N-2] (Note that there are n insertion points in total)
CodeAs follows:
/** Recursive solution first divides the string into a [0, 1 ,..., n-2] And a [n-1], and then recursively solve ,..., n-2], insert a [n-1] to ,..., n-2] all arranged (note a total of N insertion points) **/vector permutate (string s) {vector V; If (S. size () = 1) v. push_back (s); else {string a = S. substr (S. size ()-1, 1); string T = S. substr (0, S. size ()-1); vector VT = permutate (t); For (vector: iterator it = vt. begin (); it! = Vt. end (); It ++) {for (INT I = 0; I <= it-> size (); I ++) {string TMP = * it; TMP. insert (I, a); V. push_back (TMP) ;}} return V ;}
[Method 2] Iteration Method
First, add the first character to the set, and then add the following characters one by one
When each character is added, it is inserted into each string that is already in the set, and the inserted string is added to the set.
Delete a string after it is inserted.
However, if there is no string of the current size, it enters the next loop.
The Code is as follows:
/** Loop solution first adds the first character to the set, and then inserts the following characters into each string that is already in the set when each character is added one by one, and add the inserted string to the collection. If the string is deleted but does not have the current size, enter the next loop **/vector permutate_loop (string s) {vector V; For (INT I = 0; I <S. size (); I ++) {string a = S. substr (I, 1); If (v. empty () v. push_back (a); else {While (v. begin ()-> size () <I + 1) {string Fr = * v. begin (); For (Int J = 0; j <= Fr. size (); j ++) {string TMP (FR); TMP. insert (J, a); V. push_back (TMP);} v. erase (v. begin () ;}} return V ;}
Test code:
/** Test code **/INT main () {string s; while (CIN> S) {cout <v = permutate_loop (s); For (vector :: iterator it = v. begin (); it! = V. End (); It ++) cout <* It <Endl; cout <Endl;} return 0 ;}