Given a set of
elements, the problem is to print all possible permutations of this set. For example, if the set is (1,2,3), then the set of permutations is {(1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1)}.
Looking at the case of four elements (1,2,3,4). The answer can be constructed by writing
1. ‘1’ followed by all the permutations of (2,3,4)
2. ‘2’ followed by all the permutations of (1,3,4)
3. ‘3’ followed by all the permutations of (1,2,4)
4. ‘4’ followed by all the permutations of (1,2,3)
A recursive method to implement the above idea is as follows:
Consider the case of (1,2,3,4), that is, n=4.
1. Place the set elements in a global array, and set the position index “k” as 0.
2. Use a for-loop to “swap” (or exchange) the 1st element with the 1st element, the 2nd element, the 3rd element, and the 4th element, respectively.
l In each loop-iteration:
i. increment the position index “k” by 1 (for considering only the remaining elements in the following recursive call);
ii. use the updated k to recursively call your permutation function;
iii. note that because you use a global array, remember to swap back the two elements after the iteration.
3. In a recursive-call path, when k reaches n, it means that you get a possible permutation.
You can use the following incomplete code to solve this problem.
|
#include
void Show(int n); void Swap(int k, int i); void Perm(int k, int n); char list[9]={'1','2','3','4','5','6','7','8','9'};
int main(void) { int num; scanf("%d",&num); Perm(0,num); return 0; }
void Show(int n) { int i; printf("(%c", list[0]); for (i=1; i printf(",%c", list[i]); } printf(")\n"); }
void Swap(int k, int i) { char temp; /*your code*/ }
void Perm(int k, int n) { int i; if(k==n) { /*print your answer*/ } else { for(i=k; i { /*your code*/ } } } |
The decimal number n that represents the number of elements in the set.
(
)
In the output you should print all the permutations.
Be sure to add a newline character '\n' at the end of each line.