LeetCode每日一题(790. Domino and Tromino Tiling)

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.

Example 2:

Input: n = 1
Output: 1

Constraints:

  • 1 <= n <= 1000

一个 board 我们从左往右排 tile, 分两种情况, 一种是排满,也就是是个严格的矩形, 另一种是部分排满,是一个矩形缺少右上角的一个方块或者右下角的一个方块。

假设 f(k)代表排满长度为 k 的 board 的排列方法的数量, p(k)代表部分排满长度为 k 的 board 的排列方法数量。这里要注意 p(k)当中的 k 要理解为缺一个角的矩形的长度,而不是多一个角的矩形的长度, 例如题中的 Tromino tile 它的长度是 2 而不是 1。还有要注意的是部分排满的情况我们只考虑缺右上角或者右下角的一种, 因为这两种情况是对称的

f(k) = f(k-1) + f(k-2) + 2 * p(k-1)
f(k)的情况可以从如下三种情况转换而来:

  1. f(k-1)再加一条竖着的 Domino tile
  2. f(k-2)加两条竖着的 Domino tile 或者加两条横着的 Domino tile
  3. p(k-1)加上对应的 Tromino tile, 因为有两种缺角情况所以乘以 2

impl Solution {
    pub fn num_tilings(n: i32) -> i32 {
        if n == 1 {
            return 1;
        }
        if n == 2 {
            return 2;
        }
        const M: i64 = 10i64.pow(9) + 7;
        let mut f = vec![0i64; n as usize];
        let mut p = vec![0i64; n as usize];
        f[0] = 1;
        f[1] = 2;
        p[1] = 1;
        for i in 2..n as usize {
            f[i] = (f[i - 1] + f[i - 2] + 2 * p[i - 1]) % M;
            p[i] = (p[i - 1] + f[i - 2]) % M;
        }
        *f.last().unwrap() as i32
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值