The full permutation non-recursive algorithm for strings is to look for sequences that are larger than the previous sequence, such as:
Starting point: The smallest arrangement of the dictionary order, for example 12345
End point: The largest sequence of dictionaries, such as 54321
Procedure: Generates the next permutation of the dictionary order that is just larger than the current arrangement.
Algorithm process: Post-search, small-size, swap, flip
After: The last ascending position in the string I, that is s[k]>s[k+1] (k>i),s[i]<s[i+1];
Find (Small Large): s[i+1...n-1] in the smallest value than AI sj;
Exchange: SI,SJ;
Flip: s[i+1...n-1]
The code is as follows:
1#include <iostream>2#include <string>3 using namespacestd; 4 5 //Exchange 6 voidSwapChar&C1,Char&C2)7 { 8 Chartemp =C1; 9C1 =C2;TenC2 =temp; One } A - //Flip - voidReverse_string (string&STR,int from,intto ) the { - while( from<to ) - { -Swap (str[ from+ +], str[to--]); + } - } + A //to find the lowest value subscript at intFind_min (stringStrint from,intto ) - { - CharMin = str[ from]; - intj = from; - if( from==to ) - { in returnJ; - } to for(inti = from+1; I <= to; ++i) + { - //find the smallest value larger than str[from-1] the if(Str[i] <= min && str[i] > str[ from-1]) * { $Min =Str[i];Panax Notoginsengj =i; - } the } + returnJ; A } the + voidPermutation_2 (string&STR,int from,intto ) - { $ stringend_str (str); $Reverse_string (END_STR, from, to); -cout << str <<Endl; - while(str! =end_str) the { - inti = from; Wuyi intj =to ; the while(I! =j) - { Wu if(Str[j-1] <Str[j]) - { About Break; $ } -j--; - } - intMin =Find_min (str, J, to); ASwap (str[j-1], str[min]); +reverse_string (str, J, to); thecout << str <<Endl; - } $ //Flip Str back . theReverse_string (str, from, to); the } the the intMainintargcConst Char*argv[]) - { in stringstr ="1223"; the intLen =str.size (); thePermutation_2 (str,0, Len-1); About return 0; the}
Results:
Note: C++stl has integrated next_permutation in the algorithm. You can sort the given string a[0...n-1] first in ascending order, and then call Next_permutation in turn to return false, which completes the non-recursive full permutation algorithm.
Full array of strings-non-recursive algorithms