The Indian Engineer

Problem 790 Domino and Tromino Tiling

Posted on 6 mins

Dynamic-Programming

Problem Statement

Link - Problem 790

Question

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 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:

Solution

class Solution {
public:
    int numTilings(int n) {
        const int MOD = 1e9 + 7;
        vector<long long> dp(max(4, n + 1), 0);
        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] + dp[i - 3]) % MOD;
        }

        return dp[n];
    }
};

Complexity Analysis

| Algorithm           | Time Complexity | Space Complexity |
| ------------------- | --------------- | ---------------- |
| Dynamic Programming | O(n)            | O(n)             |

Explanation

Intial Thoughts

To solve this problem, consider the board as a series of units that need to be covered. Think about how each type of tile can cover these units and how the arrangement of tiles affects the overall number of ways to tile the board. Key points include: breaking down the problem into smaller parts, understanding how tiles can be arranged, recognizing patterns in tiling, considering the role of the tromino shape, and identifying a method to keep track of the number of ways to tile the board. Additionally, consider the constraints and how they impact the solution, such as the size of the board and the available tiles.

Intuitive Analysis

To intuitively solve this problem, think about the tiling process step by step, focusing on how each new tile adds to the existing arrangement. Consider the following points: the base cases for small boards, how adding a new column to the board changes the possibilities, the relationship between the number of ways to tile a board of size n and the number of ways to tile smaller boards, the role of dynamic programming in tracking these relationships, and how to use these insights to calculate the number of ways to tile a board of any given size. Furthermore, consider the importance of avoiding overcounting and ensuring that each arrangement is unique, and how the modulo operation can help manage large numbers of possibilities.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.