Problem
Given a 3 × N rectangle, determine the number of ways to tile it using tiles of size 1 × 3 (horizontal tromino) and 3 × 1 (vertical tromino). You may place tiles only with integer grid alignment; tiles cannot overlap or go outside the board.
Input: integer N (1 ≤ N ≤ 15)
Output: number of distinct tilings of a 3 × N board using the given tiles.
Examples
Example 1
| |
Solution
This is a standard tiling/counting DP. Let f(n) be the number of ways to tile a 3 × n board. There are two mutually exclusive choices for filling the leftmost part of the board:
- Place a single vertical
3×1tile in column 1 — this reduces the problem to3 × (n-1)and contributesf(n-1)ways. - Place three horizontal
1×3tiles (one in each row) covering columns1..3— this reduces to3 × (n-3)and contributesf(n-3)ways.
Therefore the recurrence is:
f(n) = f(n-1) + f(n-3)
With base cases f(0) = 1 (empty board), f(1) = 1 (one vertical column), and f(2) = 1 (two vertical columns). This recurrence matches the sample: f(4) = f(3) + f(1) = 2 + 1 = 3.
We present a simple bottom-up DP implementation and path-free counting (only counts ways).
Method 1 — Bottom-up DP (iterative)
Intuition
Fill the board from left to right. At each step either consume one column with a vertical tile or consume three columns with three horizontals. This yields a linear recurrence depending only on smaller n values.
Approach
- Handle small
ndirectly: return1forn = 0,1,2as base cases. - Allocate array
dp[0..n]and setdp[0]=dp[1]=dp[2]=1. - For
ifrom3toncomputedp[i] = dp[i-1] + dp[i-3]. - Return
dp[n].
Edge cases: N may be 0 (empty board) — treat f(0)=1.
Code
| |
| |
| |
| |
Complexity
- ⏰ Time complexity:
O(n)— compute values fordp[3..n]with constant work each step. - 🧺 Space complexity:
O(n)for thedparray. This can be reduced toO(1)by keeping only the last three values.