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
X
Given N, how many ways are there to tile a 2 x N board? Return your answer modulo 10^9 + 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:
Input: 3
Output: 5
Explanation:
The five different ways are listed below, different letters indicates different tiles:
XYZ XXZ XYY XXY XYY
XYZ YYZ XZZ XYY XXY
Note:
- N will be in range
[1, 1000]
.
这个题目看着真像俄罗斯方块啊,哈哈哈。
这个题目很自然地让我想到了DP,所以先找状态转移方程。
首先思考 N = 0 时,有几个呢? 这个地方其实是有歧义的,我试探了一下测试集,发现是1,就当它是1吧,其实如果不是对后面的影响也不大。
当N =1时,显然只有一种情况; 当N = 2时,有两种情况:
xx xy
yy xy
当N=3时,有如下几种情况:
有5种,最左边可以理解为f(3-1), 中间可以理解为f(3-2), 最右边可以理解为f(3-3);似乎我们得出了转移方程了
我们再思考N=4,,我们看一下面一种情况:
这样就又得到了两种排列的可能(另一种是旋转180°得到)。
这样随着N不断增大我们总能找到像上图这样“犬牙交错”的排列方式,这样得到了通项公式:
得到
这样我们得到了转移方程,即可得到答案。
注意要求过大的数要模10^9+7!
代码:
class Solution {
public:
int numTilings(int N) {
if( N == 0 )
return 1;
else if( N == 1 )
return 1;
else if( N == 2 )
return 2;
int n = 3;
int x0 = 1;
int x1 = 1;
int x2 = 2;
while( n <= N ){
long long temp = (long long)2*x2 + x0;
x0 = x1;
x1 = x2;
x2 = temp % 1000000007LL;
++n;
}
return x2;
}
};