Problem:
Permutation Enumeration

For given an integer $n$, print all permutations of $\{1, 2, ..., n\}$ in lexicographic order.

Input

An integer $n$ is given in a line.

Output

Print each permutation in a line in order. Separate adjacency elements by a space character.

Constraints

$1 \leq n \leq 9$

Sample Input 1

2

Sample Output 1

1 2
2 1

Sample Input 2

3

Sample Output 2

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

Solution in JAVA (judge verdict: Time Limit Exceeded)

import java.util.Scanner;

public class Main {
	public static void main(String[] args){
		try (Scanner sc = new Scanner(System.in)) {
			StringBuilder str = new StringBuilder();
			int n = sc.nextInt();
			for(int i = 1; i < n + 1; i++) {
				str.append(i);
			}
			permutation(str.toString(),"");
		}
	}
	public static void permutation(String q, String ans){
		if(q.length() <= 1) {
			for(int i = 0; i < ans.length(); i++) {
				System.out.print(ans.substring(i, i + 1) + " ");
			}
			System.out.println(q);
		}
		else {
			for (int i = 0; i < q.length(); i++) {
				permutation(q.substring(0, i) + q.substring(i + 1), ans + q.charAt(i));
			}
		}
	}
}