Listing Square Arrangements in Lexicographic Order
InterviewTime limit1sMemory limit128 MB
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 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 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 the 7 arrangements above are written as
Given , write a program that outputs every possible arrangement in lexicographic order. Here . Lexicographic order is defined as follows: for two arrangements and , arrangement is printed before when , or when there exists an integer such that and .
Input
The first line contains the integer .
Output
Print every arrangement in lexicographic order, one per line, followed by a trailing newline. An arrangement is printed as the integers in this order, separated by single spaces.