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 show above.

Example 2:

Input: n = 1
Output: 1

Constraints:
  • 1 <= n <= 1000

From: LeetCode

Link: 790. Domino and Tromino Tiling


Solution:

Ideas:
  1. Define a recurrence relation to calculate the number of tilings for a board of width n.
  2. The base cases will be small widths for which we can manually count the number of tilings.
  3. For larger widths, we build up the solution from the base cases, using the recurrence relation.
  4. We need to consider the last column which could be filled by:
    • A vertical domino, which leaves the subproblem of tiling a 2 x (n-1) board.
    • Two horizontal dominos, which leaves the subproblem of tiling a 2 x (n-2) board.
    • A tromino along with a domino, which will lead to two subproblems: tiling a 2 x (n-2) board and a 2 x (n-3) board.
  5. Since the answer can be very large, we will return it modulo 1 0 9 + 7 10^9+7 109+7.
Caode:
c 复制代码
int numTilings(int n) {
    if (n == 1) return 1;
    if (n == 2) return 2;
    if (n == 3) return 5;

    long dp[n+1];
    dp[0] = 1; dp[1] = 1; dp[2] = 2; dp[3] = 5;

    for (int i = 4; i <= n; ++i) {
        dp[i] = (2 * dp[i-1] % 1000000007 + dp[i-3]) % 1000000007; // Main recurrence relation
    }

    return (int) dp[n];
}
相关推荐
luj_17681 小时前
塔防牌:策略与卡牌的智慧碰撞
服务器·c语言·开发语言·经验分享·算法
wuyk5552 小时前
3.链表:用指针串联的动态数据结构
c语言·开发语言·数据结构·链表
郝学胜-神的一滴2 小时前
干货版《算法导论》17:二叉树核心原理、遍历逻辑与高阶实操全解
数据结构·c++·python·算法·计算机·编程
爱编程的小新☆2 小时前
【LeetCode】从递归到 Flood Fill:5 道题吃透 DFS 的选择、回溯与标记
java·算法·leetcode·深度优先·回溯·flood fill
Water_Sunzhipeng2 小时前
2024牛客暑期多校训练营1
算法
hetao17338372 小时前
2026-08-09~08-14 hetao1733837 的刷题记录
c++·算法
技术小黑2 小时前
RNN算法实战系列06 | LSTM 实现糖尿病探索与预测
rnn·算法·lstm
evans在进步2 小时前
LeetCode 33:搜索旋转排序数组——Java 两阶段二分查找详解
java·python·leetcode
Lzh编程小栈2 小时前
【嵌入式底层】SPI超透彻详解:通信原理、四线结构、四种模式、寄存器底层 + 面试全集
c语言·stm32·单片机·面试·职场和发展
疯狂打码的少年3 小时前
【数据结构】二叉树的性质(五大性质+计算)
数据结构·笔记·算法