LeetCode 题解工作台
不同的好子序列数目
给你一个二进制字符串 binary 。 binary 的一个 子序列 如果是 非空 的且没有 前导 0 (除非数字是 "0" 本身),那么它就是一个 好 的子序列。 请你找到 binary 不同好子序列 的数目。 比方说,如果 binary = "001" ,那么所有 好 子序列为 ["0", "0…
2
题型
5
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们定义 表示以 结尾的不同好子序列的数目,定义 表示以 结尾的且以 开头的不同好子序列的数目。初始时 $f = g = 0$。 对于一个二进制字符串,我们可以从左到右遍历每一位,假设当前位为 ,那么:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个二进制字符串 binary 。 binary 的一个 子序列 如果是 非空 的且没有 前导 0 (除非数字是 "0" 本身),那么它就是一个 好 的子序列。
请你找到 binary 不同好子序列 的数目。
- 比方说,如果
binary = "001",那么所有 好 子序列为["0", "0", "1"],所以 不同 的好子序列为"0"和"1"。 注意,子序列"00","01"和"001"不是好的,因为它们有前导 0 。
请你返回 binary 中 不同好子序列 的数目。由于答案可能很大,请将它对 109 + 7 取余 后返回。
一个 子序列 指的是从原数组中删除若干个(可以一个也不删除)元素后,不改变剩余元素顺序得到的序列。
示例 1:
输入:binary = "001" 输出:2 解释:好的二进制子序列为 ["0", "0", "1"] 。 不同的好子序列为 "0" 和 "1" 。
示例 2:
输入:binary = "11" 输出:2 解释:好的二进制子序列为 ["1", "1", "11"] 。 不同的好子序列为 "1" 和 "11" 。
示例 3:
输入:binary = "101" 输出:5 解释:好的二进制子序列为 ["1", "0", "1", "10", "11", "101"] 。 不同的好子序列为 "0" ,"1" ,"10" ,"11" 和 "101" 。
提示:
1 <= binary.length <= 105binary只含有'0'和'1'。
解题思路
方法一:动态规划
我们定义 表示以 结尾的不同好子序列的数目,定义 表示以 结尾的且以 开头的不同好子序列的数目。初始时 。
对于一个二进制字符串,我们可以从左到右遍历每一位,假设当前位为 ,那么:
- 如果 ,那么我们可以在 和 个不同的好子序列拼上 ,因此更新 ;
- 如果 ,那么我们可以在 和 个不同的好子序列拼上 ,同时还可以单独拼上 ,因此更新 。
如果字符串包含 ,那么最终答案为 ,否则答案为 。
时间复杂度 ,其中 是字符串长度。空间复杂度 。
相似题目:
class Solution:
def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
f = g = 0
ans = 0
mod = 10**9 + 7
for c in binary:
if c == "0":
g = (g + f) % mod
ans = 1
else:
f = (f + g + 1) % mod
ans = (ans + f + g) % mod
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check the candidate's understanding of dynamic programming and state transitions.
- question_mark
Evaluate their approach to handling large input sizes efficiently.
- question_mark
Look for the ability to handle modular arithmetic correctly in solutions.
常见陷阱
外企场景- error
Forgetting to account for leading zeros in subsequences except '0'.
- error
Mismanaging the modulo operation, leading to overflow or incorrect results.
- error
Not ensuring subsequences are unique, resulting in overcounting.
进阶变体
外企场景- arrow_right_alt
Count subsequences where no subsequence can contain both '0' and '1'.
- arrow_right_alt
Find the number of good subsequences where each subsequence contains at least one '1'.
- arrow_right_alt
Return the sum of lengths of all unique good subsequences modulo 10^9 + 7.