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];
}
相关推荐
小O的算法实验室15 小时前
2026年ASOC,基于深度强化学习的无人机三维复杂环境分层自适应导航规划方法,深度解析+性能实测
算法·无人机·论文复现·智能算法·智能算法改进
qq_3395548215 小时前
英飞凌ModusToolbox环境搭建
c语言·eclipse
张張40816 小时前
(域格)环境搭建和编译
c语言·开发语言·python·ai
郭涤生16 小时前
STL vector 扩容机制与自定义内存分配器设计分析
c++·算法
༾冬瓜大侠༿16 小时前
vector
c语言·开发语言·数据结构·c++·算法
Ricky111zzz16 小时前
leetcode学python记录1
python·算法·leetcode·职场和发展
汀、人工智能16 小时前
[特殊字符] 第58课:两个正序数组的中位数
数据结构·算法·数据库架构··数据流·两个正序数组的中位数
liu****16 小时前
第16届省赛蓝桥杯大赛C/C++大学B组(京津冀)
开发语言·数据结构·c++·算法·蓝桥杯
汀、人工智能16 小时前
[特殊字符] 第79课:分割等和子集
数据结构·算法·数据库架构·位运算·哈希表·分割等和子集
独小乐16 小时前
009.中断实践之实现按键测试|千篇笔记实现嵌入式全栈/裸机篇
linux·c语言·驱动开发·笔记·嵌入式硬件·arm