All problems
0547MediumMathDynamic ProgrammingTreeBinary Search TreeBinary Tree

Shapes of the Docket Registry

Tracked in this browser only
Write code

Trains the technique from

LeetCode 96Unique Binary Search Trees

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A claims office files dockets numbered 1 through n into a search tree. Each docket occupies exactly one node, and each node has at most two nodes hanging off it, one called its lower child and one called its upper child.

The filing rule is that for every node, every docket sitting anywhere beneath its lower child carries a smaller number, and every docket sitting anywhere beneath its upper child carries a larger number.

Two registries are considered different when some docket has a different lower child or a different upper child in one than in the other. Return how many different registries can be built from dockets 1 through n.

Examples

Example 1

Input
n = 6
Output
132

Six dockets can be filed in 132 different registries.

Example 2

Input
n = 9
Output
4862

Nine dockets can be filed in 4862 different registries.

Example 3

Input
n = 4
Output
14

With four dockets there are 14 registries. Putting docket 2 at the top, for instance, forces docket 1 into its lower branch and leaves dockets 3 and 4 for the upper branch, which they can fill in two ways.

Constraints

  • 1 <= n <= 25
  • The largest allowed n gives an answer of 4861946401452, so every answer stays below 5 * 10^12.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def num_trees(n: int) -> int:
Java
public long numTrees(int n)
September 7
Apply