Print the full array of strings
The idea of the algorithm:
Divides a string into two parts, the first character + all the characters in the back part. This allows the entire process to be solved recursively:
1. Each character is given the first character 2. When a character is the first character, the whole arrangement of all the following characters is used, and the whole arrangement of all the characters behind it can be regarded as the sub-problem of recursion.
Full-lined recursive tree:
But here's another problem: when there are duplicate characters in the string, such an algorithm increases the number of final results. For example, the full array of string aab,a+ab, and then swap or a+ab the full array. So it increases the number of results. The solution is to jump over a repeating character and not to recursively.
So the code implements:
#include <iostream> #include <algorithm>using namespace std;void getpermutation (char *pstr, char *pbegin); void permutation (char *pstr), void permutation (char *pstr) {if (pStr = = NULL) {return;} Getpermutation (PSTR, pStr);} void Getpermutation (char *pstr, char *pbegin) {if (*pbegin = = ' + ') {printf ("%s\n", PSTR);} Else{for (char *pch = pbegin; *pch! = '); ++pch) {//If it is the same character, then it is not recursive to prevent the generation of extra string results if (*pch = *pbegin && pCh! = P Begin) Continue;swap (*pch, *pbegin); Getpermutation (PSTR, Pbegin + 1); Swap (*pch, *pbegin);}}} Getpermutationint Main () {char str[] = "AAB";//the argument here if it is char *str = "abc"; is not feasible because the constant string is not exchangeable permutation (str); return 0;}
This is the C language version of the implementation, and then see the C + + version of the implementation:
vector<string> permutation (string str) {vector<string> res;if (str.size () = = 0) return res;getpermutation ( Res, str, 0); sort (Res.begin (), Res.end ()); return res;} void Getpermutation (vector<string>& res, string& str, int begin) {if (begin = = Str.size ()) {Res.push_back ( STR);} else{for (unsigned int i = begin; I < str.size (); i++) {if (str[i] = = Str[begin] && i!! Begin) Continue;swap (str[i ], Str[begin]); Getpermutation (res, str, begin + 1), swap (Str[i], str[begin]);} For}}//getpermutation
String full permutation and combination algorithm