LeetCode 题解工作台
选择建筑的方案数
给你一个下标从 0 开始的二进制字符串 s ,它表示一条街沿途的建筑类型,其中: s[i] = '0' 表示第 i 栋建筑是一栋办公楼, s[i] = '1' 表示第 i 栋建筑是一间餐厅。 作为市政厅的官员,你需要随机 选择 3 栋建筑。然而,为了确保多样性,选出来的 3 栋建筑 相邻 的两栋不能…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
根据题目描述,我们需要选择 栋建筑,且相邻的两栋不能是同一类型。 我们可以枚举中间的建筑,假设为 ,那么左右两边的建筑类型只能是 $x \oplus 1$,其中 表示异或运算。因此,我们可以使用两个数组 和 分别记录左右两边的建筑类型的数量,然后枚举中间的建筑,计算答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始的二进制字符串 s ,它表示一条街沿途的建筑类型,其中:
s[i] = '0'表示第i栋建筑是一栋办公楼,s[i] = '1'表示第i栋建筑是一间餐厅。
作为市政厅的官员,你需要随机 选择 3 栋建筑。然而,为了确保多样性,选出来的 3 栋建筑 相邻 的两栋不能是同一类型。
- 比方说,给你
s = "001101",我们不能选择第1,3和5栋建筑,因为得到的子序列是"011",有相邻两栋建筑是同一类型,所以 不合 题意。
请你返回可以选择 3 栋建筑的 有效方案数 。
示例 1:
输入:s = "001101" 输出:6 解释: 以下下标集合是合法的: - [0,2,4] ,从 "001101" 得到 "010" - [0,3,4] ,从 "001101" 得到 "010" - [1,2,4] ,从 "001101" 得到 "010" - [1,3,4] ,从 "001101" 得到 "010" - [2,4,5] ,从 "001101" 得到 "101" - [3,4,5] ,从 "001101" 得到 "101" 没有别的合法选择,所以总共有 6 种方法。
示例 2:
输入:s = "11100" 输出:0 解释:没有任何符合题意的选择。
提示:
3 <= s.length <= 105s[i]要么是'0',要么是'1'。
解题思路
方法一:计数 + 枚举
根据题目描述,我们需要选择 栋建筑,且相邻的两栋不能是同一类型。
我们可以枚举中间的建筑,假设为 ,那么左右两边的建筑类型只能是 ,其中 表示异或运算。因此,我们可以使用两个数组 和 分别记录左右两边的建筑类型的数量,然后枚举中间的建筑,计算答案即可。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
class Solution:
def numberOfWays(self, s: str) -> int:
l = [0, 0]
r = [s.count("0"), s.count("1")]
ans = 0
for x in map(int, s):
r[x] -= 1
ans += l[x ^ 1] * r[x ^ 1]
l[x] += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They hint that only 010 and 101 matter, which is a direct push away from checking all triples.
- question_mark
They ask for a linear solution under length 10^5, so any nested loop over candidate triples is dead on arrival.
- question_mark
They mention Dynamic Programming and Prefix Sum together, which usually means counting subsequences through running state totals rather than recursion.
常见陷阱
外企场景- error
Counting contiguous substrings instead of subsequences, which misses valid picks with gaps between buildings.
- error
Updating DP states in the wrong order and accidentally reusing the current character twice in one transition.
- error
Using a 32-bit integer even though the number of valid triples can grow large for long strings.
进阶变体
外企场景- arrow_right_alt
Count alternating subsequences of length k instead of exactly three buildings.
- arrow_right_alt
Return separate counts for pattern 010 and pattern 101 rather than their total.
- arrow_right_alt
Generalize from a binary string to a small alphabet and count subsequences with no equal adjacent selected characters.