This page is still under construction.

Parts of this page are still being built. What you see may change.

Listing Square Arrangements in Lexicographic Order

Interview

Time limit1sMemory limit128 MB

Summary
List every partition of n whose parts are non-increasing, and print the sequences in decreasing lexicographic order.
Level

Medium5 of 10

Topics
Backtracking, Recursion, Implementation, Combinatorics
Solved
No attempts yet

Problem

There are nn squares of the same size. Arrange them into several columns with their bottom edges aligned horizontally. Adjacent columns must be placed so that the left column is never lower than the right column (that is, the heights are non-increasing from left to right). For example, when n=5n = 5 there are the following 7 possible arrangements.

Each arrangement is represented by the sequence of the number of squares stacked in each column, read from left to right. For instance, when n=5n = 5 the 7 arrangements above are written as

(5)(4,1)(3,2)(3,1,1)(2,2,1)(2,1,1,1)(1,1,1,1,1)(5)\quad (4, 1)\quad (3, 2)\quad (3, 1, 1)\quad (2, 2, 1)\quad (2, 1, 1, 1)\quad (1, 1, 1, 1, 1)

Given nn, write a program that outputs every possible arrangement in lexicographic order. Here n≤30n \le 30. Lexicographic order is defined as follows: for two arrangements (a1,a2,…,as)(a_1, a_2, \ldots, a_s) and (b1,b2,…,bt)(b_1, b_2, \ldots, b_t), arrangement (a1,a2,…,as)(a_1, a_2, \ldots, a_s) is printed before (b1,b2,…,bt)(b_1, b_2, \ldots, b_t) when a1>b1a_1 > b_1, or when there exists an integer i>1i > 1 such that a1=b1,…,ai−1=bi−1a_1 = b_1, \ldots, a_{i-1} = b_{i-1} and ai>bia_i > b_i.

Input

The first line contains the integer nn.

Output

Print every arrangement in lexicographic order, one per line, followed by a trailing newline. An arrangement (a1,a2,…,as)(a_1, a_2, \ldots, a_s) is printed as the integers a1,a2,…,asa_1, a_2, \ldots, a_s in this order, separated by single spaces.

Examples1

  1. Example 1

    Input
    5
    
    Expected output
    5
    4 1
    3 2
    3 1 1
    2 2 1
    2 1 1 1
    1 1 1 1 1