Permutations
mediumRecursion & Backtracking+20 XPTime limit 2s
Print all permutations (orderings) of n distinct integers.
Input:
- line 1:
n - line 2:
ndistinct integers
Output: every permutation on its own line (numbers separated by spaces), in lexicographic order (compare number by number).
Constraints: 1 ≤ n ≤ 7, −10 ≤ value ≤ 10.
Think about it: backtracking with a used[] array: at each position, try every unused number. If you sort the numbers first and try them in order, the output is already lexicographic. (n = 7 means 5 040 lines — build the output in one buffer and print it once.)
Sample input 1
3 1 2 3
Sample output 1
1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1
Sample input 2
2 0 1
Sample output 2
0 1 1 0
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).