10833 - Permutations of Set   

Description

Given a set of n≧1 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,2,1), (3,1,2)}.

 

<Hint1>

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)

 

<Hint2>

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.
    • In each loop-iteration:
      1. increment the position index “k” by 1 (for considering only the remaining elements in the following recursive call);
      2. use the updated k to recursively call your permutation function;
      3. 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.

 

Note that

1.      This problem involves three files.

  • function.h: Function definition of show, Swap and Perm.
  • function.c: Function describe of show, Swap and Perm.
  • main.c: A driver program to test your implementation.

You will be provided with main.c and function.h, and asked to implement function.c.

2.     For OJ submission:

       Step 1. Submit only your function.c into the submission block. (Please choose c compiler) 

       Step 2. Check the results and debug your program if necessary.

function.h

main.c

function.c

Input

The decimal number n that represents the number of elements in the set.

(1≦n≦5)

Output

In the output you should print all the permutations.

Be sure to add a newline character '\n' at the end of each line.

Sample Input  Download

Sample Output  Download

Partial Judge Code

10833.c

Partial Judge Header

10833.h

Tags

10401HW8



Discuss