Proposal Description:
Enter a positive integer N, and output all the first n numbers in the lexicographically ascending order.
Two-way analysis:
Solve this problem with recursion: first output all the arrangements starting with 1 (recursive call), then output the arrangement starting with 2 (recursive call), and then the arrangement starting with 3, finally, it is arranged starting with N.
The arrangement starting with 1 has the following characteristics: the first is 1, followed by 2 ~ 9. Therefore, the following parameters are required for designing recursive functions:
(1) identified "prefix" sequence for output;
(2) a set of elements that need to be fully arranged so that the first element can be selected in sequence. Write the following pseudo code:
Void print_permutation (sequence a, set S)
{
If (S is empty) output sequence;
Else considers each element V of S in ascending order.
{
Print_permutation (add V to the end of a to obtain the new sequence, S-{v });
}
}
In the above recursive function, when the recursive boundary is s empty, sequence A can be output directly. If S is not empty, every element in S is considered in the ascending order, each recursive call starts with.
The following describes how to implement the program. Use an array to represent sequence a. The set S can be completely determined by sequence A. All elements not present in sequence A can be selected. The function in C language cannot obtain the number of elements in the array when accepting array parameters. Therefore, you must specify the number of filled positions or the element location cur to be determined. Declare an array a that is large enough, and then call print_permutation (n, A, 0) to output 1 ~ All arrays of N.
AC code:
1 # include <iostream> 2 using namespace STD; 3 int s [100]; 4 void Order (int n, int * a, int cur) 5 {6 if (cur = N) 7 {for (INT I = 0; I <n; I ++) 8 cout <A [I]; 9 cout <Endl;} 10 else11 {12 for (INT I = 1; I <= N; I ++) 13 {14 int OK = 1; 15 For (Int J = 0; j <cur; j ++) // search for the number 16 if (a [J] = I) OK = 0 in the sorted sequence; 17 if (OK) // if no number exists, add it to the array 18 {19 A [cur] = I; 20 order (n, A, cur + 1 ); // if found, go to the next layer of recursion 21} 22} 23} 24} 25 int main () 26 {27 int N; 28 CIN> N; 29 Order (n, s, 0); 30 return 0; 31}