LeetCode 题解工作台

给 N x 3 网格图涂色的方案数

你有一个 n x 3 的网格图 grid ,你需要用 红,黄,绿 三种颜色之一给每一个格子上色,且确保相邻格子颜色不同(也就是有相同水平边或者垂直边的格子颜色不同)。 给你网格图的行数 n 。 请你返回给 grid 涂色的方案数。由于答案可能会非常大,请你返回答案对 10^9 + 7 取余的结果。 …

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

困难 · 状态·转移·动态规划

bolt

答案摘要

把每一行所有可能的状态进行分类。根据对称性原理,当一行只有 个元素时,所有合法状态分类为 型以及 型。 - 当状态为 型时:下一行可能的状态为 , , , , 。这 个状态可归纳为 个 型,以及 个 型。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

你有一个 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.length
  • grid[i].length == 3
  • 1 <= n <= 5000
lightbulb

解题思路

方法一:递推

把每一行所有可能的状态进行分类。根据对称性原理,当一行只有 33 个元素时,所有合法状态分类为 010010 型以及 012012 型。

  • 当状态为 010010 型时:下一行可能的状态为 101101, 102102, 121121, 201201, 202202。这 55 个状态可归纳为 33010010 型,以及 22012012 型。
  • 当状态为 012012 型时:下一行可能的状态为 101101, 120120, 121121, 201201。这 44 个状态可归纳为 22010010 型,以及 22012012 型。

综上所述,可以得到 newf0=3×f0+2×f1\text{newf0} = 3 \times f0 + 2 \times f1, newf1=2×f0+2×f1\text{newf1} = 2 \times f0 + 2 \times f1

时间复杂度 O(n)O(n),其中 nn 是网格的行数。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

给 N x 3 网格图涂色的方案数题解:状态·转移·动态规划 | LeetCode #1411 困难