Leetcode-790. Domino and Tromino Tiling 多米诺和托米诺平铺 (DP)

探讨使用多米诺和托米诺瓷砖平铺2xN面板的算法,通过动态规划解决计数问题,给出两种高效实现方法并分析其时间与空间复杂度。

题目

有两种形状的瓷砖:一种是 2x1 的多米诺形,另一种是形如 “L” 的托米诺形。两种形状都可以旋转。
XX <- 多米诺
XX <- “L” 托米诺
X
给定 N 的值,有多少种方法可以平铺 2 x N 的面板?返回值 mod 10^9 + 7。
(平铺指的是每个正方形都必须有瓷砖覆盖。两个平铺不同,当且仅当面板上有四个方向上的相邻单元中的两个,使得恰好有一个平铺有一个瓷砖占据两个正方形。)
链接:https://leetcode.com/problems/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.)

Note:

  • N will be in range [1, 1000].

Example:

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

思路及代码

DP 1. 规律

# 36ms 58.13%
class Solution:
    def numTilings(self, N: int) -> int:
        if not N:
            return 1
        kmod = 10**9 + 7
        mino = [[0,0,0] for i in range(N+1)]
        mino[0][0] = 1
        mino[1][0] = 1
        for i in range(2, N+1):
            mino[i][0] = (mino[i-1][0] + mino[i-2][0] + mino[i-1][1] + mino[i-1][2]) % kmod
            mino[i][1] = (mino[i-1][2] + mino[i-2][0]) % kmod
            mino[i][2] = (mino[i-1][1] + mino[i-2][0]) % kmod
        return mino[N][0]

DP 2. 公式
  • dp[n] = dp[n-1] + dp[n-2] + 2*(dp[n-3] + … + dp[0])
    = dp[n-1] + dp[n-3] + [dp[n-2] + dp[n-3] + 2*(dp[n-4] + … + dp[0])]
    = dp[n-1] + dp[n-3] + dp[n-1]
    = 2*dp[n-1] + dp[n-3]
  • dp[n-1]:在此基础上加一个|
  • dp[n-2]:在此基础上加=
  • dp[n-3]……dp[0]:在此基础上插入两个L型在最边缘,对于每一个共两种
  • 故dp[n] = 2*dp[n-1]+dp[n-3]
# 20ms 99.59%
class Solution:
    def numTilings(self, N: int) -> int:
        mino = [1,1,2]
        if not N:
            return 0
        if N < 3:
            return mino[N]
        kmod = 10**9 + 7
        for i in range(3, N+1):
            mino.append((2*mino[-1] + mino[-3]) % kmod)
        return mino[-1]

复杂度

T = O(n)O(n)O(n)
S = O(n)O(n)O(n) -> O(1)O(1)O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值