[Post] string Arrangement

Source: Internet
Author: User

Post: http://zhedahht.blog.163.com/blog/static/254111742007499363479/

Question: enter a string to print all the characters in the string, such as the string ABC, all strings ABC, ACB, Bac, BCA, cab, and CBA that can be arranged by characters A, B, and C are output.

Analysis: This is a good programming question for understanding recursion, so it has frequently appeared in interviews and pen questions of major companies in the past year.

Take the three-character ABC as an example to analyze the process of string arrangement. First, we fix the first character a and find the arrangement of the next two characters BC. After the two BC characters are arranged properly, we exchange the first character a with the second character B to obtain the BAC. Then we fix the first character B and find the arrangement of the next two characters AC. Now is the time to place C in the first place. Remember that we have exchanged the first character a with the second character B. To ensure that C is still in the first position, before we exchange C and the first character, we need to exchange B and. After exchanging B and A, exchange C with a in the first position to obtain the CBA. We fix the first character C again and find the arrangement of the next two characters B and.

Since we already know how to arrange the three characters, it is a typical recursive idea to fix the first character and then arrange the last two characters. Based on the previous analysis, we can get the following reference code:

1 void permutation (char * pstr, char * pbegin); // function declaration
2
3 /////////////////////////////////////// //////////////////////////////////
4 // get the permutation of a string,
5 // For example, input string ABC, its permutation is
6 // abc acb bac bca CBA cab
7 /////////////////////////////////////// //////////////////////////////////
8 void permutation (char * pstr)
9 {
10 permutation (pstr, pstr );
11}
12
13 /////////////////////////////////////// //////////////////////////////////
14 // print the permutation of a string,
15 // input: pstr-input string
16 // pbegin-points to the begin char of string
17 // which we want to permutate in this Recursion
18 /////////////////////////////////////// //////////////////////////////////
19 void permutation (char * pstr, char * pbegin)
20 {
21 if (! Pstr |! Pbegin) return;
22
23 // If pbegin points to the end of string,
24 // This round of permutation is finished,
25 // print the permuted string
26 if (* pbegin = '\ 0 '){
27 printf ("% s \ n", pstr );
28}
29 // otherwise, permute string
30 else {
31 For (char * PCH = pbegin; * PCH! = '\ 0'; ++ PCH)
32 {
33 // swap PCH and pbegin
34 char temp = * PCH;
35 * PCH = * pbegin;
36 * pbegin = temp;
37
38 permutation (pstr, pbegin + 1 );
39
40 // restore PCH and pbegin
41 temp = * PCH;
42 * PCH = * pbegin;
43 * pbegin = temp;
44}
45}
46}
void my_permutation(char *str, int len, int index)
{
if (str == NULL) return;
if (index == len) cout << str << endl;
for (int i = index; i < len; i++) {
SWAP(str[i], str[index]);
my_permutation(str, len, index+1);
SWAP(str[i], str[index]);
}
}

Extended 1: What should I do if I want to find not all the characters, but all the combinations of characters? When the input string contains the same string, the same character exchange position is different, but the same combination. For example, if ABC is input, its combination includes a, B, c, AB, AC, BC, and ABC.

Extension 2: enter an array containing eight numbers to determine whether the eight numbers can be placed on the eight vertices of the cube, the sum of the four vertices on the opposite surface of the cube is equal.

--------------------------------------------------------------

Extended: Eight queens

Question: Eight queens are placed on 8x8 chess sets so that they cannot attack each other. That is, two queens cannot be on the same row, column, or diagonal slashes, how many methods are there in total.

Any two of the eight queens cannot be in the same row, that is, each Queen occupies a row and can define an array of columnindex [8]. the number I in the array indicates the column number of the Queen in the row I. First, initialize the eight columnindex numbers with 0-7, respectively. Next we need to arrange the columnindex in full. Since we use different numbers to initialize numbers in the array, any two queens must have different columns. We only need to determine whether the eight queens corresponding to each arrangement are on the same diagonal slashes, that is, the two subscripts I and J of the array, is it I-j = columnindex [I]-column [J] Or J-I = columnindex [I]-columnindex [J]?

Int g_number = 0;

Void eightqueen ()
{
Const int queens = 8;
Int columnindex [queens];
For (INT I = 0; I <Queens; ++ I)
Columnindex [I] = I;
Permutation (columnindex, Queens, 0 );
}

Void permutation (INT columnindex [], int length, int index)
{
If (Index = length ){
If (check (columnindex, length )){
++ G_number;
Printqueen (columnindex, length );
}
}
Else {
For (INT I = index; I <length; ++ I ){
Swap (columnindex [I], columnindex [Index]);
Permutation (columnindex, length, index + 1 );
Swap (columnindex [I], columnindex [Index]);
}
}
}

Bool check (INT columnindex [], int length) // determines whether the full arrangement meets the conditions
{
For (INT I = 0; I <length; ++ I ){
For (Int J = I + 1; j <length; ++ J ){
If (I-j = columnindex [I]-columnindex [J])
| (J-I = columnindex [I]-columnindex [J])
Return false;
}
}
Return true;
}

Void printqueen (INT columnindex [], int length)
{
Printf ("solution % d \ n", g_number );
For (INT I = 0; I <length; ++ I)
Cout <columnindex [I] <"";
Cout <Endl;
}

Although complicated, the context is clear ~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.