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.

思路:

 

 

 看的花花的视频,还是递推推倒得来的,我觉得面试不可能遇见,遇见就是对方不想要你;

class Solution {
    public int numTilings(int n) {
        int MOD = 1000000007;
        // define:
        // dp[i][0]: ways to cover i cols, both row of col i are covered;
        // dp[i][1]: ways to cover i cols, top row of col i is covered;
        // dp[i][2]: ways to cover i cols, bottom row of col i is covered;
        
        // init: dp[0][0] = dp[1][0] = 1;
        
        // dp[i][0] = dp[i - 1][0] + dp[i - 2][0] + 2 * dp[i - 1][1];
        // dp[i][1] = dp[i - 2][0] + dp[i - 1][2];
        // dp[i][2] = dp[i - 2][0] + dp[i - 1][1]; 
        
        // dp[i][1] always equals to dp[i][2];
        
        // so we can simplify:
        // dp[i][0] = dp[i - 1][0] + dp[i - 2][0] + 2 * dp[i - 1][1];
        // dp[i][1] = dp[i - 2][0] + dp[i - 1][1];
        
        long[][] dp = new long[n + 1][2];
        dp[0][0] = dp[1][0] = 1;
        for(int i = 2; i <= n; i++) {
            dp[i][0] = (dp[i - 1][0] + dp[i - 2][0] + 2 * dp[i - 1][1]) % MOD;
            dp[i][1] = (dp[i - 2][0] + dp[i - 1][1]) % MOD;
        }
        return (int)dp[n][0];
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值