Problem 285
All Permutations
Medium · 20 pts · Array, Backtracking
Problem
You are given N distinct integers. Print every permutation (ordering) of them, one per line, with the values separated by spaces. There are N! permutations. List them in lexicographic order: compare two permutations element by element by numeric value, and the first difference decides which comes first. Sort the numbers first. Then a backtracking search that, at each position, tries the unused numbers in increasing order produces the permutations already in the right order. Alternatively, repeatedly apply the next-permutation algorithm.
Input
First line: integer N. Second line: N distinct integers.
Output
Print N! lines, each a permutation with values space-separated.
Constraints
1 <= N <= 6; -10 <= A[i] <= 10
Example input
3 1 2 3
Example output
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
Explanation
The values 1, 2 and 3 have 3! = 6 orderings. Starting with 1 gives 1 2 3 and 1 3 2, starting with 2 gives 2 1 3 and 2 3 1, and starting with 3 gives 3 1 2 and 3 2 1.