#790 Domino and Tromino Tiling

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(k1) f ( k − 2 ) f(k-2) f(k2) 都有1种转换到 f ( k ) f(k) f(k) 的方式
  • f ( 0 ) f(0) f(0) f ( k − 3 ) f(k-3) f(k3) 都有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[n1]+f[n2]+2(f[n3]+...+f[0])=f[n1]+f[n2]+f[n3]+f[n3]+2(f[n4]+...+f[0])=f[n1]+f[n3]+(f[n2]+f[n3]+2(f[n4]+...+f[0]))=f[n1]+f[n3]+f[n1]=2f[n1]+f[n3]

ok,那状态转移方程也解决了(以上公式推导依旧来自于discuss,我自己算的时候漏算了后面的 2 ∗ g ( x ) 2*g(x) 2g(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];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值