LeetCode 题解工作台

统计构造好字符串的方案数

给你整数 zero , one , low 和 high ,我们从空字符串开始构造一个字符串,每一步执行下面操作中的一种: 将 '0' 在字符串末尾添加 zero 次。 将 '1' 在字符串末尾添加 one 次。 以上操作可以执行任意次。 如果通过以上过程得到一个 长度 在 low 和 high 之…

category

1

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们设计一个函数 表示从第 位开始构造的好字符串的个数,答案即为 。 函数 的计算过程如下:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你整数 zero ,one ,low 和 high ,我们从空字符串开始构造一个字符串,每一步执行下面操作中的一种:

  • 将 '0' 在字符串末尾添加 zero  次。
  • 将 '1' 在字符串末尾添加 one 次。

以上操作可以执行任意次。

如果通过以上过程得到一个 长度 在 low 和 high 之间(包含上下边界)的字符串,那么这个字符串我们称为  字符串。

请你返回满足以上要求的 不同 好字符串数目。由于答案可能很大,请将结果对 109 + 7 取余 后返回。

 

示例 1:

输入:low = 3, high = 3, zero = 1, one = 1
输出:8
解释:
一个可能的好字符串是 "011" 。
可以这样构造得到:"" -> "0" -> "01" -> "011" 。
从 "000" 到 "111" 之间所有的二进制字符串都是好字符串。

示例 2:

输入:low = 2, high = 3, zero = 1, one = 2
输出:5
解释:好字符串为 "00" ,"11" ,"000" ,"110" 和 "011" 。

 

提示:

  • 1 <= low <= high <= 105
  • 1 <= zero, one <= low
lightbulb

解题思路

方法一:记忆化搜索

我们设计一个函数 dfs(i)dfs(i) 表示从第 ii 位开始构造的好字符串的个数,答案即为 dfs(0)dfs(0)

函数 dfs(i)dfs(i) 的计算过程如下:

  • 如果 i>highi \gt high,返回 00
  • 如果 lowihigh low \leq i \leq high,答案累加 11,然后 ii 之后既可以添加 zero00,也可以添加 one11,因此答案累加上 dfs(i+zero)+dfs(i+one)dfs(i + zero) + dfs(i + one)

过程中,我们需要对答案取模,并且可以使用记忆化搜索减少重复计算。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 n=highn = high

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
        @cache
        def dfs(i):
            if i > high:
                return 0
            ans = 0
            if low <= i <= high:
                ans += 1
            ans += dfs(i + zero) + dfs(i + one)
            return ans % mod

        mod = 10**9 + 7
        return dfs(0)
speed

复杂度分析

指标
时间O(\text{high})
空间O(\text{high})
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for the candidate's understanding of dynamic programming and state transitions.

  • question_mark

    Check if the candidate can optimize the space complexity by reducing it to O(1).

  • question_mark

    Evaluate whether the candidate can describe how to handle the edge cases like when low equals high.

warning

常见陷阱

外企场景
  • error

    Overcomplicating the space complexity by not using the state transition optimization.

  • error

    Not handling the case where low equals high correctly, leading to incorrect counting.

  • error

    Confusing the number of valid strings with the number of operations to generate them.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Adjust the problem to only count strings with a fixed length instead of a range.

  • arrow_right_alt

    Introduce a limit on the number of '1' or '0' that can be appended at each step.

  • arrow_right_alt

    Extend the problem to include additional binary operations or different characters.

help

常见问题

外企场景

统计构造好字符串的方案数题解:状态·转移·动态规划 | LeetCode #2466 中等