leetcode#790. Domino and Tromino Tiling

790. Domino and Tromino Tiling

Problem Description

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.

Solution

It is not difficult to think of dynamic programming after reading the problem. However, the design of the recurrent formula is the key points. Initially, we set dp[0] = dp[1] = 1 and dp[2] = 2 for convenience. When n > 3, we cover the tiles square by square. There are three cases:

  1. Add an “XX” tile vertically and step one square forward.
  2. Add two “XX” tile horizontally and step two square forward.
  3. Add a combination of two trominos and X - 3 dominos and step X square forward.

Thus we get a recurrent formula:

dp[n] = dp[n-1] + dp[n-2] + 2 * \sum_{i=0}^{n-3} dp[i]

To speed up the calculation, we use an array to store the data. Notice that the answer should modulo 1e9+7. Here is my code:

class Solution {
public:
    int numTilings(int N) {
        int md = 1e9+7;
        long long tiles[1005];
        tiles[0] = 1;
        tiles[1] = 1;
        tiles[2] = 2;

        for (int i=3; i <= N; i++) {
            tiles[i] = tiles[i-1] + tiles[i-2];
            for (int j=0; j <= i-3; j++) {
                tiles[i] += 2 * tiles[j];
                tiles[i] %= md;
            }
        }
        return tiles[N];
    }
};

And the formula can be simplified into the form as below, and the proof is omitted:

dp[n] = 2 * dp[n-1] + dp[n-3]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值