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];
}
相关推荐
Blossom.1186 小时前
大模型自动化压缩:基于权重共享的超网神经架构搜索实战
运维·人工智能·python·算法·chatgpt·架构·自动化
优选资源分享6 小时前
MD5 哈希值校验工具 v1.5.3 实用文件校验工具
算法·哈希算法
AI科技星6 小时前
能量绝对性与几何本源:统一场论能量方程的第一性原理推导、验证与范式革命
服务器·人工智能·科技·线性代数·算法·机器学习·生活
Coder_Boy_6 小时前
基于SpringAI的在线考试系统-数据库表设计
java·数据库·算法
散峰而望6 小时前
【算法竞赛】链表和 list
数据结构·c++·算法·链表·list·哈希算法·推荐算法
Legendary_0086 小时前
从DC接口改成Type-C:LDR6328芯片助力传统设备升级快充体验
c语言·开发语言
至为芯6 小时前
IP5385至为芯支持C口双向快充的30W到100W移动电源方案芯片
c语言·开发语言
爱编程的小吴6 小时前
【力扣练习题】55. 跳跃游戏
算法·leetcode
春日见6 小时前
控制算法:PID算法
linux·运维·服务器·人工智能·驱动开发·算法·机器人
Maỿbe6 小时前
常见的垃圾收集算法
java·jvm·算法