LeetCode 题解工作台
给 N x 3 网格图涂色的方案数
你有一个 n x 3 的网格图 grid ,你需要用 红,黄,绿 三种颜色之一给每一个格子上色,且确保相邻格子颜色不同(也就是有相同水平边或者垂直边的格子颜色不同)。 给你网格图的行数 n 。 请你返回给 grid 涂色的方案数。由于答案可能会非常大,请你返回答案对 10^9 + 7 取余的结果。 …
1
题型
6
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
把每一行所有可能的状态进行分类。根据对称性原理,当一行只有 个元素时,所有合法状态分类为 型以及 型。 - 当状态为 型时:下一行可能的状态为 , , , , 。这 个状态可归纳为 个 型,以及 个 型。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
你有一个 n x 3 的网格图 grid ,你需要用 红,黄,绿 三种颜色之一给每一个格子上色,且确保相邻格子颜色不同(也就是有相同水平边或者垂直边的格子颜色不同)。
给你网格图的行数 n 。
请你返回给 grid 涂色的方案数。由于答案可能会非常大,请你返回答案对 10^9 + 7 取余的结果。
示例 1:
输入:n = 1 输出:12 解释:总共有 12 种可行的方法:![]()
示例 2:
输入:n = 2 输出:54
示例 3:
输入:n = 3 输出:246
示例 4:
输入:n = 7 输出:106494
示例 5:
输入:n = 5000 输出:30228214
提示:
n == grid.lengthgrid[i].length == 31 <= n <= 5000
解题思路
方法一:递推
把每一行所有可能的状态进行分类。根据对称性原理,当一行只有 个元素时,所有合法状态分类为 型以及 型。
- 当状态为 型时:下一行可能的状态为 , , , , 。这 个状态可归纳为 个 型,以及 个 型。
- 当状态为 型时:下一行可能的状态为 , , , 。这 个状态可归纳为 个 型,以及 个 型。
综上所述,可以得到 , 。
时间复杂度 ,其中 是网格的行数。空间复杂度 。
class Solution:
def numOfWays(self, n: int) -> int:
mod = 10**9 + 7
f0 = f1 = 6
for _ in range(n - 1):
g0 = (3 * f0 + 2 * f1) % mod
g1 = (2 * f0 + 2 * f1) % mod
f0, f1 = g0, g1
return (f0 + f1) % mod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to identify dynamic programming state transitions.
- question_mark
Understanding of how to apply modulo operations in large-number problems.
- question_mark
Proficiency in applying recursive relations to problems involving grid configurations.
常见陷阱
外企场景- error
Failing to consider the adjacency constraint, leading to invalid configurations.
- error
Not using the modulo operation correctly, potentially resulting in overflow errors.
- error
Misunderstanding dynamic programming transitions, causing incorrect state updates.
进阶变体
外企场景- arrow_right_alt
Increase grid size to n x m, requiring generalized state transition management.
- arrow_right_alt
Implement an approach that handles multiple constraints, such as limiting the number of color changes in each row.
- arrow_right_alt
Consider variations with additional constraints like coloring each row in a specific pattern or requiring fewer colors.