Description
Recursion is used to generate a full array of sets, which is also a frequent problem during the test interview. The problem of full arrangement generally requires recursive or non-recursive solutions. The full arrangement of non-recursive output sets in order is introduced in my other blog (http://blog.csdn.net/syzcch/article/details/8136218 ), this section describes how to recursively generate a full array of sets.
Recursive thinking
The method of recursive solution to this question is relatively simple compared with the non-recursive solution. An example can be used to illustrate:
If the set element is {1, 2}, the initial sequence is 1 2, and 2 is obtained through the exchange of 1 and 2. The two sequences are generated.
If the element of the set is {1, 2, 3}, the initial sequence is 1 2 3, and 2 and 3 are transposed to generate a sequence 1 3 2.
Return to the initial sequence 1 2 3, change the positions of 2 and 1 to obtain the sequence 2 1 3, and then change the positions of 1 and 3 to obtain another sequence 2 3 1.
Return to the initial sequence 1 2 3 again. This time, 3 and 1 are transposed to obtain the sequence 3 2 1, and then 2 and 1 are transposed to obtain another sequence 3 1 2.
In this way, the Set: 1 2 3 is derived from the set {1, 2, 3 }.
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
All the sorting that can be produced by this set is produced, which completes the purpose of this question.
The above idea is easy to understand, and it is easy to see that recursive solution is very convenient. The following is the specific sample code.
Sample Code
void quansort(char *src,char *begin){char *pc;if('\0'==*begin){printf(" %s ",src);return;}for(pc=begin;*pc!='\0';pc++){char tmp;tmp=*pc;*pc=*begin;*begin=tmp;quansort(src,begin+1);tmp=*pc;*pc=*begin;*begin=tmp;}}
void main(){char p[4]="abc";quansort(p,p);}
Summary
The full arrangement of recursive and non-recursive production sets is a basic small algorithm, which requires understanding of its ideas and mastering the problem-solving methods.