Http://blog.csdn.net/v_july_v/article/details/6879101
Title: Enter a string that prints all the permutations of the characters in the string.
For example, input string abc, output all strings that can be arranged by character A, B, c
ABC, ACB, BAC, BCA, Cab and CBA.
Analysis: This question was originally collated in last year's Microsoft interview 100 question 53rd question, second time finishing in Microsoft, Google and other companies very good face questions and answers [第61-70 question] 67th question. Coincidentally, this year again appeared in this year's 2011.10.09 Baidu test question. OK, next, let's have a good analysis of the problem.
First, recursive implementation
Each element is selected sequentially from the set, as the first element of the arrangement, and then the remaining elements are arranged in full, so that they are recursively processed so that all the elements are arranged in full order. As an example of a full array of string ABC, we can do this: take ABC as an example
Fixed a, ask the arrangement of the following BC: ABC,ACB, after A and b exchange, get BAC
Fixed B, for the back of the arrangement of AC: BAC,BCA, after the good, C put to the first position, to get the CBA
Fixed c, for the following BA arrangement: Cba,cab. The code can be written as shown below
#include <iostream>
using namespace std;
void permutation (char* pstr, char* pbegin);
void permutation (char* pstr)
{
permutation (pstr, pstr);
}
void permutation (char* pstr, char* pbegin)
{
if (!pstr | |!pbegin) return
;
if (*pbegin = = ' ")
{
printf ("%s\n ", pstr);
}
else
{for
(char* pCh = pbegin; *pch!= '; + + pch ')
{
//swap pch and pbegin
char temp = *pch;
*pch = *pbegin;
*pbegin = temp;
Permutation (pstr, Pbegin + 1);
Restore pCh and pbegin
temp = *pch;
*pch = *pbegin;
*pbegin = temp;
}} int main ()
{
char str[] ={' A ', ' B ', ' C ', ' d ', ' yes '};
Permutation (str);
GetChar ();
return 0;
}