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 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 show above.
思路:
看的花花的视频,还是递推推倒得来的,我觉得面试不可能遇见,遇见就是对方不想要你;
class Solution {
public int numTilings(int n) {
int MOD = 1000000007;
// define:
// dp[i][0]: ways to cover i cols, both row of col i are covered;
// dp[i][1]: ways to cover i cols, top row of col i is covered;
// dp[i][2]: ways to cover i cols, bottom row of col i is covered;
// init: dp[0][0] = dp[1][0] = 1;
// dp[i][0] = dp[i - 1][0] + dp[i - 2][0] + 2 * dp[i - 1][1];
// dp[i][1] = dp[i - 2][0] + dp[i - 1][2];
// dp[i][2] = dp[i - 2][0] + dp[i - 1][1];
// dp[i][1] always equals to dp[i][2];
// so we can simplify:
// dp[i][0] = dp[i - 1][0] + dp[i - 2][0] + 2 * dp[i - 1][1];
// dp[i][1] = dp[i - 2][0] + dp[i - 1][1];
long[][] dp = new long[n + 1][2];
dp[0][0] = dp[1][0] = 1;
for(int i = 2; i <= n; i++) {
dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + 2 * dp[i - 1][1]) % MOD;
dp[i][1] = (dp[i - 2][0] + dp[i - 1][1]) % MOD;
}
return (int)dp[n][0];
}
}