790. Domino and Tromino Tiling
You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo
1
0
9
+
7
10^9 + 7
109+7.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
Example 1:
Input: n = 3
Output: 5
Explanation: The five different ways are shown above.
Example 2:
Input: n = 1
Output: 1
Constraints:
- 1 <= n <= 1000
From: LeetCode
Link: 790. Domino and Tromino Tiling
Solution:
Ideas:
-
Base cases:
- dp[0] = 1 (empty board)
- dp[1] = 1 (one vertical domino)
- dp[2] = 2 (two horizontal OR two vertical dominoes)
-
Recurrence relation: dp[i] = dp[i-1] + dp[i-2] + 2*dp[i-3]
-
Three ways to build a 2×i board:
- Take a 2×(i-1) solution + add 1 vertical domino
- Take a 2×(i-2) solution + add 2 horizontal dominoes
- Take a 2×(i-3) solution + add tromino combinations (2 symmetric patterns)
-
Key insight: The factor of 2 in 2*dp[i-3] accounts for the two different ways tromino pieces can be arranged to fill a 2×3 gap
Code:
int numTilings(int n) {
const int MOD = 1000000007;
if (n <= 0) return 0;
if (n == 1) return 1;
if (n == 2) return 2;
// dp[i] represents number of ways to tile 2×i board
// We need to consider the different ways to fill the rightmost columns
long long dp[n+1];
dp[0] = 1; // Base case: empty board
dp[1] = 1; // One vertical domino
dp[2] = 2; // Two ways: (two horizontal) OR (two vertical)
// For each position i >= 3, we can:
// 1. Take dp[i-1] and add a vertical domino (1 way)
// 2. Take dp[i-2] and add two horizontal dominoes (1 way)
// 3. Take dp[i-3] and add a tromino + domino combination (2 ways)
// This accounts for the L-shaped tromino patterns
for (int i = 3; i <= n; i++) {
dp[i] = (dp[i-1] + dp[i-2] + 2 * dp[i-3]) % MOD;
}
return (int)dp[n];
}