Skip to content
Problem 790 · LeetCode 790(opens in a new tab)

Domino and Tromino Tiling

MediumDynamic programming

You have an unlimited supply of two kinds of tiles: a domino, which covers two cells side by side, and a tromino, an L shape that covers three cells. Both may be turned in any direction.

Count the ways to cover a board 2 cells tall and n cells wide so that every cell is covered by exactly one tile and nothing hangs off the edge. Two tilings count as different when their tiles are placed differently. The count can be huge, so return it modulo 1,000,000,007.

Example 1

Input:  n = 5
Output: 24
Why:    8 tilings use only dominoes, 16 use trominoes
2 more examples and the constraints

Example 2

Input:  n = 2
Output: 2
Why:    two upright dominoes, or two flat ones

Example 3

Input:  n = 4
Output: 11
Why:    5 tilings use only dominoes, 6 use trominoes

Constraints

  • 1 ≤ n ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Two edge shapesO(n)
  2. One recurrenceO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 1,000Verdict
Two edge shapesO(n)
Passes; shows where the rule comes from
One recurrenceO(n)
Best; one line per column

n = width of the board.

Edge cases to test

  • n = 1. Only one upright domino fits: 1. The tables must not read below index 0.
  • n = 2. A tromino cannot fit alone, so the answer is 2.
  • Large n. The count overflows quickly; take the modulo on every step and use 64-bit math.
  • Trominoes come in pairs. One tromino leaves a jagged edge; only a second tromino or flat dominoes can close it.

Common mistakes

  • Counting the tromino closing once instead of twice: the edge can stick out on the top or the bottom.
  • Using the domino-only rule dp[i] = dp[i − 1] + dp[i − 2], which forgets trominoes.
  • Doing 2 · dp[i − 1] in 32-bit integers, which overflows before the modulo.

How to talk through it

  1. 1Clarify. Can tiles rotate? Is the board always 2 tall? Do we return the count modulo 1,000,000,007?
  2. 2Draw small boards. List n = 1, 2, 3 by hand: 1, 2, 5. That gives the base cases and a check.
  3. 3Name the edge shapes. Flat or one cell sticking out. Write how each shape grows by one column.
  4. 4Simplify. Subtract the rule for i − 1 from the rule for i to get dp[i] = 2 · dp[i − 1] + dp[i − 3].
  5. 5Test out loud. Check n = 3 gives 5 and n = 4 gives 11 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?