LeetCode 题解工作台
统计构造好字符串的方案数
给你整数 zero , one , low 和 high ,我们从空字符串开始构造一个字符串,每一步执行下面操作中的一种: 将 '0' 在字符串末尾添加 zero 次。 将 '1' 在字符串末尾添加 one 次。 以上操作可以执行任意次。 如果通过以上过程得到一个 长度 在 low 和 high 之…
1
题型
4
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们设计一个函数 表示从第 位开始构造的好字符串的个数,答案即为 。 函数 的计算过程如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你整数 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 <= 1051 <= zero, one <= low
解题思路
方法一:记忆化搜索
我们设计一个函数 表示从第 位开始构造的好字符串的个数,答案即为 。
函数 的计算过程如下:
- 如果 ,返回 ;
- 如果 ,答案累加 ,然后 之后既可以添加
zero个 ,也可以添加one个 ,因此答案累加上 。
过程中,我们需要对答案取模,并且可以使用记忆化搜索减少重复计算。
时间复杂度 ,空间复杂度 。其中 。
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(\text{high}) |
| 空间 | O(\text{high}) |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.