790. Domino and Tromino Tiling

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);似乎我们得出了转移方程了

f(n) = f(n-1) +f(n-2) + 2f(n-3)

我们再思考N=4,f(4) = f(3) + f(2) + 2f(1) ?,我们看一下面一种情况:

这样就又得到了两种排列的可能(另一种是旋转180°得到)。

这样随着N不断增大我们总能找到像上图这样“犬牙交错”的排列方式,这样得到了通项公式:

\begin{align*} f(n) &= f(n-1)+f(n-2)+2f(n-3)+......+2f(0) \\ &= f(n-1)+f(n-2)+2\sum_{0}^{n-3}{f(i)} \end{align*}

得到

\begin{align*} f(n) &= f(n-1)+f(n-2) + 2f(n-3) + 2\sum_{0}^{n-4}{f(i)} \\&= f(n-1) + f(n-2) + f(n-3) + 2\sum_{0}^{n-4}{f(i)} + f(n-3) \\&= f(n-1) + f(n-1) + f(n-3) \\&= 2f(n-1) + f(n-3) \end{align*}

这样我们得到了转移方程,即可得到答案。

注意要求过大的数要模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;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值