LeetCode //C - 790. Domino and Tromino Tiling

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 1 0 9 + 7 10^9 + 7 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 shown above.

Example 2:

Input: n = 1
Output: 1

Constraints:
  • 1 <= n <= 1000

From: LeetCode
Link: 790. Domino and Tromino Tiling


Solution:

Ideas:
  • Base cases:

    • dp[0] = 1 (empty board)
    • dp[1] = 1 (one vertical domino)
    • dp[2] = 2 (two horizontal OR two vertical dominoes)
  • Recurrence relation: dp[i] = dp[i-1] + dp[i-2] + 2*dp[i-3]

  • Three ways to build a 2×i board:

    • Take a 2×(i-1) solution + add 1 vertical domino
    • Take a 2×(i-2) solution + add 2 horizontal dominoes
    • Take a 2×(i-3) solution + add tromino combinations (2 symmetric patterns)
  • Key insight: The factor of 2 in 2*dp[i-3] accounts for the two different ways tromino pieces can be arranged to fill a 2×3 gap

Code:
int numTilings(int n) {
    const int MOD = 1000000007;
    
    if (n <= 0) return 0;
    if (n == 1) return 1;
    if (n == 2) return 2;
    
    // dp[i] represents number of ways to tile 2×i board
    // We need to consider the different ways to fill the rightmost columns
    
    long long dp[n+1];
    dp[0] = 1;  // Base case: empty board
    dp[1] = 1;  // One vertical domino
    dp[2] = 2;  // Two ways: (two horizontal) OR (two vertical)
    
    // For each position i >= 3, we can:
    // 1. Take dp[i-1] and add a vertical domino (1 way)
    // 2. Take dp[i-2] and add two horizontal dominoes (1 way)  
    // 3. Take dp[i-3] and add a tromino + domino combination (2 ways)
    //    This accounts for the L-shaped tromino patterns
    
    for (int i = 3; i <= n; i++) {
        dp[i] = (dp[i-1] + dp[i-2] + 2 * dp[i-3]) % MOD;
    }
    
    return (int)dp[n];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值