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 C# (judge verdict: Time Limit Exceeded)

using System.Collections.Generic;
using System.Linq;
using System;

public static class Permi
{
    public static IEnumerable<IEnumerable<T>> Perm<T>(this IEnumerable<T> items, int? k = null)
    {
        if (k == null) k = items.Count();
        if (k == 0) yield return Enumerable.Empty<T>();
        else
        {
            var i = 0;
            foreach (var x in items)
            {
                var xs = items.Where((_, index) => i != index);
                foreach (var c in Perm(xs, k - 1))
                    yield return c.Before(x);
                i++;
            }
        }
    }
    public static IEnumerable<T> Before<T>(this IEnumerable<T> items, T first)
    {
        yield return first;
        foreach (var i in items) yield return i;
    }
}

public class Hello
{
    public static void Main()
    {
        var n = int.Parse(Console.ReadLine().Trim());
        var a = Enumerable.Range(1, n).Perm();
        var w = new int[fact(n)];
        var p = 0;
        var temp = "";
        foreach (var x in a)
        {
            temp = "";
            foreach (var xx in x)
                temp += xx.ToString();
            w[p++] = int.Parse(temp);
        }
        Array.Sort(w);
        for (int i = 0; i < w.Length; i++) print(w, i);
    }
    public static void print(int[] w, int n)
    {
        var t = w[n].ToString();
        for (int i = 0; i < t.Length; i++)
        {
            if (i == t.Length - 1) Console.WriteLine(t[i]);
            else Console.Write("{0} ", t[i]);
        }
    }
    public static int fact(int n)
    {
        var ret = 1;
        for (int i = 1; i <= n; i++) ret *= i;
        return ret;
    }
}