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];
}
相关推荐
xiaoye-duck几秒前
《算法题讲解指南:优选算法-分治-归并》--47.归并排序,48.数组中的逆序对
c++·算法
Darkwanderor1 分钟前
图论——最短路问题
c++·算法·图论·最短路
Filotimo_2 分钟前
3.4 图
算法·图论
I_LPL2 分钟前
day49 代码随想录算法训练营 图论专题2
java·算法·深度优先·图论·广度优先·求职面试
小小unicorn3 分钟前
[微服务即时通讯系统]语音子服务的实现与测试
c++·算法·微服务·云原生·架构·xcode
xsyaaaan3 分钟前
代码随想录Day53图:Floyd算法精讲_ Astar算法精讲_最短路算法总结篇_图论总结
算法·图论
lihihi4 分钟前
P10471 最大异或对 The XOR Largest Pair
算法
漫随流水16 分钟前
备战蓝桥杯(3)
数据结构·c++·算法·蓝桥杯
song85460113420 分钟前
hash和history导航区别 个别服务器为啥不支持 history 模式
服务器·算法·哈希算法
IT猿手21 分钟前
多无人机动态避障路径规划研究:基于粒子群优化算法PSO的多无人机动态避障路径规划研究(可以自定义无人机数量及起始点),MATLAB代码
算法·matlab·机器人·无人机·路径规划·动态路径规划