790. Domino and Tromino Tiling
Problem
Tile a 2×n board with 2×1 dominoes and L-shaped trominoes, both of which may be rotated. Count the tilings modulo 10⁹ + 7 (tilings differ if some pair of adjacent cells is covered by one tile in one and not in the other).
Example: n = 3 → 5; n = 1 → 1
Constraints: n ≤ 1000.
Let f(n) = tilings of a full 2 × n board and p(n) = tilings of a 2 × n board plus one protruding cell. A full board ends in a vertical domino (f(n−1)), two horizontal dominoes (f(n−2)), or a tromino that closes a protruding board (2·p(n−2), two mirror images): f(n) = f(n−1) + f(n−2) + 2·p(n−2). A protruding board ends in a tromino (f(n−1)) or a horizontal domino on the protruding row (p(n−1)): p(n) = p(n−1) + f(n−1). Subtracting consecutive fs eliminates p and gives the one-line recurrence f(n) = 2·f(n−1) + f(n−3).
n: 0 1 2 3 4 5 6
f(n): 1 1 2 5 11 24 53 f(4) = 2·5 + 1 = 11
Complexity: O(n) time, O(1) space.
class Solution:
def numTilings(self, n: int) -> int:
MOD = 10**9 + 7
a, b, c = 1, 1, 2 # f(0), f(1), f(2)
if n < 3:
return [1, 1, 2][n]
for _ in range(n - 2):
a, b, c = b, c, (2 * c + a) % MOD
return c
assert [Solution().numTilings(n) for n in range(1, 7)] == [1, 2, 5, 11, 24, 53]
# cross-check against the two-state (full / jagged) DP for larger n
f, p = [1, 1], [0, 1] # p(n): a 2 x n board plus one protruding cell
for n in range(2, 1001):
f.append((f[n - 1] + f[n - 2] + 2 * p[n - 2]) % (10**9 + 7))
p.append((p[n - 1] + f[n - 1]) % (10**9 + 7))
assert Solution().numTilings(1000) == f[1000]
assert Solution().numTilings(30) == f[30]
class Solution {
public int numTilings(int n) {
final int MOD = 1_000_000_007;
if (n < 3) return new int[]{1, 1, 2}[n];
long a = 1, b = 1, c = 2;
for (int i = 3; i <= n; i++) { long d = (2 * c + a) % MOD; a = b; b = c; c = d; }
return (int) c;
}
}
func numTilings(n int) int {
const mod = 1_000_000_007
if n < 3 {
return []int{1, 1, 2}[n]
}
a, b, c := 1, 1, 2 // f(n) = 2 f(n-1) + f(n-3)
for i := 0; i < n-2; i++ {
a, b, c = b, c, (2*c+a)%mod
}
return c
}