Fully arranged recursive and non-recursive implementations

Source: Internet
Author: User

Full sorting is a hot topic in the test interview, because it is difficult to evaluate Recursive Implementation and non-Recursive Implementation, so as to distinguish the examinee's level. Therefore, Baidu and Xunlei have both taken the test in campus recruitment and the examination of programmers and software designers. Therefore, this article summarizes the full arrangement to help you better learn and understand. You are welcome to point out any supplement to this article.

First, let's take a look at how the question is required (Baidu Xunlei's strokes ).

Write a function in C ++, such as Foo (const char * Str), and print out the full arrangement of Str,
Such as ABC, ACB, BCA, DAC, cab, and CBA.

 

1. Recursive Implementation of full Arrangement

For convenience, use 123 as an example. 123 is arranged in the ascending order of 123, 132, 213, 231, 312, and 321. First, consider how the number 213 and 321 is obtained. Obviously, both of them are obtained from the exchange between 1 in 123 and the next two numbers. Then, we can exchange the second number of 123 and the third number to get 132. Similarly, 213 and 321 can be obtained based on 231 and 312. So you can know --The full arrangement is to switch each number from the first number to the number next to it.After finding this rule, recursive code is easily written:

[CPP]
View plaincopy
  1. // Recursive Implementation of full Arrangement
  2. # Include <stdio. h>
  3. # Include <string. h>
  4. Void swap (char * a, char * B)
  5. {
  6. Char T = *;
  7. * A = * B;
  8. * B = T;
  9. }
  10. // K indicates the number selected, and M indicates the number of the selected number.
  11. Void allrange (char * pszstr, int K, int m)
  12. {
  13. If (k = m)
  14. {
  15. Static int s_ I = 1;
  16. Printf ("% 3d arrange \ t % s \ n", s_ I ++, pszstr );
  17. }
  18. Else
  19. {
  20. For (INT I = K; I <= m; I ++) // The number of I is exchanged with the number next to it to get a new arrangement.
  21. {
  22. Swap (pszstr + k, pszstr + I );
  23. Allrange (pszstr, k + 1, M );
  24. Swap (pszstr + k, pszstr + I );
  25. }
  26. }
  27. }
  28. Void Foo (char * pszstr)
  29. {
  30. Allrange (pszstr, 0, strlen (pszstr)-1 );
  31. }
  32. Int main ()
  33. {
  34. Printf ("Recursive Implementation of full arrangement \ n ");
  35. Printf ("-- by morewindows (http://blog.csdn.net/MoreWindows) -- \ n ");
  36. Char sztextstr [] = "123 ";
  37. Printf ("% s in full order: \ n", sztextstr );
  38. Foo (sztextstr );
  39. Return 0;
  40. }

The running result is as follows:

Note that this method does not take into account repeated numbers. For example, 122 will output:

This output absolutely does not meet the requirements. Therefore, we need to remove the repeated series.

 

2. Remove repeated full-permutation recursion implementations

BecauseThe full arrangement is to switch each number from the first number to the number next to it.Let's first try to add such a judgment -- if a number is the same as the number next to it, the two numbers will not be exchanged. For example, if the number is 122, the first number is exchanged with 212 and 221. Then the second number in 122 does not need to be exchanged with the third number, but for 212, the second number is different from the third number, and 221 is obtained after the exchange. It is the same as 122 that is obtained from the exchange of the first number and the third number in 221. This method does not work.

New ThinkingFor 122, the first number 1 is exchanged with the second number 2 to get 212, and then the first number 1 is exchanged with the third number 2, because the third number is equal to the second number, therefore, the first number is no longer exchanged with the third number. Consider another 212, and the second number can be exchanged with the third number to solve 221. In this case, the full order is generated.

In this way, we also get the rule to remove duplicates in the entire arrangement --The fully arranged deduplication refers to the exchange of each number from the first number with a non-repeated number next to it.In programming, when the number of I is exchanged with the number of J, it is required that [I, j) do not have a number equal to the number of J. The complete code is provided below:

[CPP]
View plaincopy
  1. // Recursive Implementation of deduplicated and fully arranged
  2. # Include <stdio. h>
  3. # Include <string. h>
  4. Void swap (char * a, char * B)
  5. {
  6. Char T = *;
  7. * A = * B;
  8. * B = T;
  9. }
  10. // In the pszstr array, whether the numbers in [nbegin, nend) are equal to the numbers whose subscript is nend
  11. Bool isswap (char * pszstr, int nbegin, int nend)
  12. {
  13. For (INT I = nbegin; I <nend; I ++)
  14. If (pszstr [I] = pszstr [nend])
  15. Return false;
  16. Return true;
  17. }
  18. // K indicates the number selected, and M indicates the number of the selected number.
  19. Void allrange (char * pszstr, int K, int m)
  20. {
  21. If (k = m)
  22. {
  23. Static int s_ I = 1;
  24. Printf ("% 3d arrange \ t % s \ n", s_ I ++, pszstr );
  25. }
  26. Else
  27. {
  28. For (INT I = K; I <= m; I ++) // The number of I is exchanged with the number next to it to get a new arrangement.
  29. {
  30. If (isswap (pszstr, K, I ))
  31. {
  32. Swap (pszstr + k, pszstr + I );
  33. Allrange (pszstr, k + 1, M );
  34. Swap (pszstr + k, pszstr + I );
  35. }
  36. }
  37. }
  38. }
  39. Void Foo (char * pszstr)
  40. {
  41. Allrange (pszstr, 0, strlen (pszstr)-1 );
  42. }
  43. Int main ()
  44. {
  45. Printf ("Recursive Implementation of deduplicated and fully arranged \ n ");
  46. Printf ("-- by morewindows (http://blog.csdn.net/MoreWindows) -- \ n ");
  47. Char sztextstr [] = "122 ";
  48. Printf ("% s in full order: \ n", sztextstr );
  49. Foo (sztextstr );
  50. Return 0;
  51. }

The running result is as follows:

 

Okay, now we are familiar with writing recursive methods, and considering the possible repeated series problems caused by repeated data in strings. So how can we use non-recursive methods to get a full arrangement?

 

3. Non-Recursive Implementation of full Arrangement

We need to consider non-recursive implementations of Full Permutation. First, we need to consider how to calculate the next permutation of strings. For example, the next sorting of "1234" is "1243 ". As long as you repeatedly find the next arrangement of the string, the full arrangement will be solved.

How do I calculate the next permutation of strings? To consider the string "926520", we will find the increasing numbers adjacent to the first pair from the back and forth. "20" and "52" are not incrementing. "26" meets the requirements, the first digit 2 is the replacement number, and the subscript of the replacement number is called the replacement point. Then, find a minimum number that is larger than the replacement number (This number must exist ), 0 and 2 won't work. 5 can. Exchange 5 and 2 to get "956220", and then reverse the string "6220" after the replacement point to get "950226 ".

For sorting like "4321", which is already the largest, use the processing method in STL to reverse the entire string to get the sorting of the smallest "1234" and return false.

In this way, as long as a loop is added with the function of calculating the next permutation of strings, a non-recursive full permutation algorithm can be easily implemented. Based on the above ideas and the implementation source code in STL, it is not difficult to write a high quality code. It is worth noting that you can write the code for fast sorting by yourself before sorting strings (see "quick sorting of the six typical vernacular algorithms"). you can also directly use the quick sorting function in the VC Library (see quick sorting function in the VC library function). The complete code is listed below:

[CPP]
View plaincopy
  1. // Non-Recursive Implementation of full Arrangement
  2. # Include <stdio. h>
  3. # Include <stdlib. h>
  4. # Include <string. h>
  5. Void swap (char * a, char * B)
  6. {
  7. Char T = *;
  8. * A = * B;
  9. * B = T;
  10. }
  11. // Reverse Interval
  12. Void reverse (char * a, char * B)
  13. {
  14. While (A <B)
  15. Swap (A ++, B --);
  16. }
  17. // Next Arrangement
  18. Bool next_permutation (char a [])
  19. {
  20. Char * pend = a + strlen ();
  21. If (A = pend)
  22. Return false;
  23. Char * P, * q, * pfind;
  24. Pend --;
  25. P = pend;
  26. While (P! =)
  27. {
  28. Q = P;
  29. -- P;
  30. If (* P <* q) // finds the number of adjacent 2 numbers in descending order. The former number is the replacement number.
  31. {
  32. // Find the first number greater than the replacement point from the back to the front
  33. Pfind = pend;
  34. While (* pfind <= * P)
  35. -- Pfind;
  36. // Replace
  37. Swap (pfind, P );
  38. // All the values after the replacement point are reversed.
  39. Reverse (Q, pend );
  40. Return true;
  41. }
  42. }
  43. Reverse (p, pend); // if there is no next arrangement, true is returned after all is reversed.
  44. Return false;
  45. }
  46. Int qsortcmp (const void * pA, const void * pb)
  47. {
  48. Return * (char *) Pa-* (char *) Pb;
  49. }
  50. Int main ()
  51. {
  52. Printf ("fully arranged non-recursive implementations \ n ");
  53. Printf ("-- by morewindows (http://blog.csdn.net/MoreWindows) -- \ n ");
  54. Char sztextstr [] = "ABC ";
  55. Printf ("% s in full order: \ n", sztextstr );
  56. // Add sorting
  57. Qsort (sztextstr, strlen (sztextstr), sizeof (sztextstr [0]), qsortcmp );
  58. Int I = 1;
  59. Do {
  60. Printf ("% 3d arrange \ t % s \ n", I ++, sztextstr );
  61. } While (next_permutation (sztextstr ));
  62. Return 0;
  63. }

The test result is as follows:

Changing the string to "CBA" will output:

 

Now we have used recursive and non-recursive methods to solve the full arrangement problem. The following is a summary:

1.The full arrangement is to switch each number from the first number to the number next to it.

2.The fully arranged deduplication refers to the exchange of each number from the first number with a non-repeated number next to it.

3.The non-recursion of the full arrangement is to find the replacement number and the replacement point from the back to the front, and then find the first number larger than the replacement number to exchange with the replacement number, finally, all data after the point is replaced upside down.

 

Reprinted please indicate the source, original address: http://blog.csdn.net/morewindows/article/details/7370155

If this article is helpful to you, click 'ding' to support it. Your support is the greatest motivation for my writing. Thank you.

Zookeeper ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Post the code written by yourself:

# Include <iostream>
# Include <algorithm>
# Include <vector>
Using namespace STD;

Template <typename T>
Bool next_permutation (t first, t last ){
If (first = last)
Return false;
If (first = -- last)
Return false;
T p = -- last;
While (P! = First ){
T q = P;
-- P;
If (* P <* q ){
T I = last;
While (* P> = * I)
-- I;
Swap (* P, * I );
Reverse (Q, last );
Return true;
}
}
Reverse (p, last );
Return false;
}

Int main ()
{
Char CHS [] = {'A', 'B', 'C '};
Int COUNT = sizeof (CHS)/sizeof (char );
Vector <char> vchs (CHS, CHS + count );

Next_permutation (vchs. Begin (), vchs. End ());

Printf ("testvector's next_permutation: \ n ");
Vector <char >:: iterator itr;
For (itr = vchs. Begin (); itr! = Vchs. End (); itr ++ ){
Printf ("% C \ t", * itr );
}

System ("pause ");
Return 0;
}

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.