返回介绍

solution / 0700-0799 / 0790.Domino and Tromino Tiling / README_EN

发布于 2024-06-17 01:03:34 字数 3931 浏览 0 评论 0 收藏 0

790. Domino and Tromino Tiling

中文文档

Description

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:

  • 1 <= n <= 1000

Solutions

Solution 1

class Solution:
  def numTilings(self, n: int) -> int:
    @cache
    def dfs(i, j):
      if i > n or j > n:
        return 0
      if i == n and j == n:
        return 1
      ans = 0
      if i == j:
        ans = (
          dfs(i + 2, j + 2)
          + dfs(i + 1, j + 1)
          + dfs(i + 2, j + 1)
          + dfs(i + 1, j + 2)
        )
      elif i > j:
        ans = dfs(i, j + 2) + dfs(i + 1, j + 2)
      else:
        ans = dfs(i + 2, j) + dfs(i + 2, j + 1)
      return ans % mod

    mod = 10**9 + 7
    return dfs(0, 0)
class Solution {
  public int numTilings(int n) {
    long[] f = {1, 0, 0, 0};
    int mod = (int) 1e9 + 7;
    for (int i = 1; i <= n; ++i) {
      long[] g = new long[4];
      g[0] = (f[0] + f[1] + f[2] + f[3]) % mod;
      g[1] = (f[2] + f[3]) % mod;
      g[2] = (f[1] + f[3]) % mod;
      g[3] = f[0];
      f = g;
    }
    return (int) f[0];
  }
}
class Solution {
public:
  const int mod = 1e9 + 7;

  int numTilings(int n) {
    long f[4] = {1, 0, 0, 0};
    for (int i = 1; i <= n; ++i) {
      long g[4] = {0, 0, 0, 0};
      g[0] = (f[0] + f[1] + f[2] + f[3]) % mod;
      g[1] = (f[2] + f[3]) % mod;
      g[2] = (f[1] + f[3]) % mod;
      g[3] = f[0];
      memcpy(f, g, sizeof(g));
    }
    return f[0];
  }
};
func numTilings(n int) int {
  f := [4]int{}
  f[0] = 1
  const mod int = 1e9 + 7
  for i := 1; i <= n; i++ {
    g := [4]int{}
    g[0] = (f[0] + f[1] + f[2] + f[3]) % mod
    g[1] = (f[2] + f[3]) % mod
    g[2] = (f[1] + f[3]) % mod
    g[3] = f[0]
    f = g
  }
  return f[0]
}

Solution 2

class Solution:
  def numTilings(self, n: int) -> int:
    f = [1, 0, 0, 0]
    mod = 10**9 + 7
    for i in range(1, n + 1):
      g = [0] * 4
      g[0] = (f[0] + f[1] + f[2] + f[3]) % mod
      g[1] = (f[2] + f[3]) % mod
      g[2] = (f[1] + f[3]) % mod
      g[3] = f[0]
      f = g
    return f[0]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文