Description
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.
Examples
Example 1:
Input: n = 3
Output: 5
Explanation: The five different ways are show above.
Example 2:
Input: n = 1
Output: 1
思路
当然动态规划的关键就在于构建状态转移方程
这里可以先举几个例子
不难发现,对于 f ( k ) f(k) f(k) 来说
- f ( k − 1 ) f(k-1) f(k−1) 和 f ( k − 2 ) f(k-2) f(k−2) 都有1种转换到 f ( k ) f(k) f(k) 的方式
- f ( 0 ) f(0) f(0) 到 f ( k − 3 ) f(k-3) f(k−3) 都有2种转换到 f ( k ) f(k) f(k) 的方式(分别是上包裹和下包裹,中间用横过来的domino填充)
那也就变成了计算
f
[
n
]
=
f
[
n
−
1
]
+
f
[
n
−
2
]
+
2
∗
(
f
[
n
−
3
]
+
.
.
.
+
f
[
0
]
)
=
f
[
n
−
1
]
+
f
[
n
−
2
]
+
f
[
n
−
3
]
+
f
[
n
−
3
]
+
2
∗
(
f
[
n
−
4
]
+
.
.
.
+
f
[
0
]
)
=
f
[
n
−
1
]
+
f
[
n
−
3
]
+
(
f
[
n
−
2
]
+
f
[
n
−
3
]
+
2
∗
(
f
[
n
−
4
]
+
.
.
.
+
f
[
0
]
)
)
=
f
[
n
−
1
]
+
f
[
n
−
3
]
+
f
[
n
−
1
]
=
2
∗
f
[
n
−
1
]
+
f
[
n
−
3
]
\begin{aligned} f[n]&=f[n-1]+f[n-2]+ 2*(f[n-3]+...+f[0])\\ &=f[n-1]+f[n-2]+f[n-3]+f[n-3]+2*(f[n-4]+...+f[0])\\ &=f[n-1]+f[n-3]+(f[n-2]+f[n-3]+2*(f[n-4]+...+f[0]))\\ &=f[n-1]+f[n-3]+f[n-1]\\ &=2*f[n-1]+f[n-3]\\ \end{aligned}
f[n]=f[n−1]+f[n−2]+2∗(f[n−3]+...+f[0])=f[n−1]+f[n−2]+f[n−3]+f[n−3]+2∗(f[n−4]+...+f[0])=f[n−1]+f[n−3]+(f[n−2]+f[n−3]+2∗(f[n−4]+...+f[0]))=f[n−1]+f[n−3]+f[n−1]=2∗f[n−1]+f[n−3]
ok,那状态转移方程也解决了(以上公式推导依旧来自于discuss,我自己算的时候漏算了后面的 2 ∗ g ( x ) 2*g(x) 2∗g(x))
代码
class Solution {
double MODNUMBER = Math.pow(10, 9) + 7;
public int numTilings(int n) {
int[] answer = new int [n + 1];
answer[0] = 0;
answer[1] = 1;
if(n == 1)
return 1;
answer[2] = 2;
if(n == 2)
return 2;
answer[3] = 5;
if(n == 3)
return 5;
for(int i = 4; i <= n; i++){
answer[i] =
((2 * answer[i - 1]) % (int)MODNUMBER +
answer[i - 3]) % (int)MODNUMBER;
}
return answer[n];
}
}