790. Domino and Tromino Tiling
Problem Description
We have two types of tiles: a 2x1 domino shape, and an “L” tromino shape. These shapes may be rotated.
XX <- domino
XX <- “L” tromino
XGiven N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 7.
Solution
It is not difficult to think of dynamic programming after reading the problem. However, the design of the recurrent formula is the key points. Initially, we set dp[0] = dp[1] = 1
and dp[2] = 2
for convenience. When n > 3
, we cover the tiles square by square. There are three cases:
- Add an “XX” tile vertically and step one square forward.
- Add two “XX” tile horizontally and step two square forward.
- Add a combination of two trominos and X - 3 dominos and step X square forward.
Thus we get a recurrent formula:
dp[n] = dp[n-1] + dp[n-2] + 2 * \sum_{i=0}^{n-3} dp[i]
To speed up the calculation, we use an array to store the data. Notice that the answer should modulo 1e9+7. Here is my code:
class Solution {
public:
int numTilings(int N) {
int md = 1e9+7;
long long tiles[1005];
tiles[0] = 1;
tiles[1] = 1;
tiles[2] = 2;
for (int i=3; i <= N; i++) {
tiles[i] = tiles[i-1] + tiles[i-2];
for (int j=0; j <= i-3; j++) {
tiles[i] += 2 * tiles[j];
tiles[i] %= md;
}
}
return tiles[N];
}
};
And the formula can be simplified into the form as below, and the proof is omitted:
dp[n] = 2 * dp[n-1] + dp[n-3]