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];
}
相关推荐
鹿角片ljp2 小时前
KV Cache 解析
java·算法
liliangcsdn3 小时前
IVOL与偏度因子的对比测量分析
算法
free-elcmacom3 小时前
C语言字符指针与字符串字面量——从一道“剑指 Offer”笔试题说起
c语言·visual studio
threerocks4 小时前
Jev 入门第一课
算法
西柚研究生1234565 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
hetao17338375 小时前
2026-09-17 hetao1733837 的刷题记录
c++·算法
午彦琳6 小时前
2026.9.17
数据结构·算法·leetcode
木井巳7 小时前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法
怕浪猫8 小时前
从 Windows 换到 Mac 三个月,我真香了
算法·面试·架构
free-elcmacom8 小时前
C语言指针进阶——指针数组模拟二维数组,以及二级指针到底怎么理解
c语言·visual studio code