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];
}
相关推荐
khalil102021 小时前
代码随想录算法训练营Day-46 动态规划13 | 647. 回文子串、516.最长回文子序列、动态规划总结
数据结构·c++·算法·leetcode·动态规划·回文子串·回文子序列
学习3人组21 小时前
柔性排产时序算法+中间过程+阶段目标 细化表格
算法·mes
he___H21 小时前
算法快与慢--哈希+双指针
算法·leetcode·哈希算法
呃呃本21 小时前
算法题(回溯)
算法
刀法如飞21 小时前
Rust数组去重的20种实现方式,AI时代用不同思路解决问题
人工智能·算法·ai编程
yxc_inspire21 小时前
25年CCPC福建邀请赛补题
学习·算法
Raink老师21 小时前
用100道题拿下你的算法面试(链表篇-4):合并 K 个有序链表
算法·链表·面试
Liangwei Lin1 天前
LeetCode 20. 有效的括号
算法
IronMurphy1 天前
【算法四十四】322. 零钱兑换
算法
凯瑟琳.奥古斯特1 天前
力扣2760 C++滑动窗口解法
数据结构·c++·算法·leetcode·职场和发展