[LeetCode]Domino and Tromino Tiling

题目描述:

LeetCode 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].

题目大意:

有两种形状的多米诺骨牌(长条形和L形),骨牌可以旋转。

求拼成2xN的矩形的所有拼接方法的个数。

解题思路:

动态规划(Dynamic Programming)

dp[x][y]表示长度(两行的最小值)为x,末尾形状为y的拼接方法个数

y有三种可能:

0表示末尾没有多余部分

1表示第一行多出1个单元格

2表示第二行多出1个单元格

状态转移方程:

dp[x][0] = (dp[x - 1][0] + sum(dp[x - 2])) % MOD   1个竖条, 2个横条,L7, rotate(L7)

dp[x][1] = (dp[x - 1][0] + dp[x - 1][2]) % MOD    rotate(L),L + 第一行横条

dp[x][2] = (dp[x - 1][0] + dp[x - 1][1]) % MOD    L,rotate(L) + 第二行横条

Python代码:

class Solution(object):
    def numTilings(self, N):
        """
        :type N: int
        :rtype: int
        """
        MOD = 10**9 + 7
        dp = [[0] * 3 for x in range(N + 10)]
        dp[0] = [1, 0, 0]
        dp[1] = [1, 1, 1]
        for x in range(2, N + 1):
            dp[x][0] = (dp[x - 1][0] + sum(dp[x - 2])) % MOD
            dp[x][1] = (dp[x - 1][0] + dp[x - 1][2]) % MOD
            dp[x][2] = (dp[x - 1][0] + dp[x - 1][1]) % MOD
        return dp[N][0]

 

本文链接:http://bookshadow.com/weblog/2018/02/25/leetcode-domino-and-tromino-tiling/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

评论
  1. DennyZhang DennyZhang 发布于 2018年2月27日 06:57 #

    比较新颖的DP题。出题者比较赞。

    经常看博主的解答,还有收获。能加个微信吗?

    Email: contact at dennyzhang.com

张贴您的评论