LeetCode 题解工作台
一和零
给你一个二进制字符串数组 strs 和两个整数 m 和 n 。 请你找出并返回 strs 的最大子集的长度,该子集中 最多 有 m 个 0 和 n 个 1 。 如果 x 的所有元素也是 y 的元素,集合 x 是集合 y 的 子集 。 示例 1: 输入: strs = ["10", "0001", "…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示在前 个字符串中,使用 个 0 和 个 1 的情况下最多可以得到的字符串数量。初始时 ,答案为 ,其中 是数组 的长度。 对于 ,我们有两种决策:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个二进制字符串数组 strs 和两个整数 m 和 n 。
请你找出并返回 strs 的最大子集的长度,该子集中 最多 有 m 个 0 和 n 个 1 。
如果 x 的所有元素也是 y 的元素,集合 x 是集合 y 的 子集 。
示例 1:
输入:strs = ["10", "0001", "111001", "1", "0"], m = 5, n = 3
输出:4
解释:最多有 5 个 0 和 3 个 1 的最大子集是 {"10","0001","1","0"} ,因此答案是 4 。
其他满足题意但较小的子集包括 {"0001","1"} 和 {"10","1","0"} 。{"111001"} 不满足题意,因为它含 4 个 1 ,大于 n 的值 3 。
示例 2:
输入:strs = ["10", "0", "1"], m = 1, n = 1
输出:2
解释:最大的子集是 {"0", "1"} ,所以答案是 2 。
提示:
1 <= strs.length <= 6001 <= strs[i].length <= 100strs[i]仅由'0'和'1'组成1 <= m, n <= 100
解题思路
方法一:动态规划
我们定义 表示在前 个字符串中,使用 个 0 和 个 1 的情况下最多可以得到的字符串数量。初始时 ,答案为 ,其中 是数组 的长度。
对于 ,我们有两种决策:
- 不选第 个字符串,此时 ;
- 选第 个字符串,此时 ,其中 和 分别是第 个字符串中 和 的数量。
我们取两种决策中的最大值,即可得到 的值。
最终的答案即为 。
时间复杂度 ,空间复杂度 。其中 是数组 的长度;而 和 分别是字符串中 和 的数量上限。
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
sz = len(strs)
f = [[[0] * (n + 1) for _ in range(m + 1)] for _ in range(sz + 1)]
for i, s in enumerate(strs, 1):
a, b = s.count("0"), s.count("1")
for j in range(m + 1):
for k in range(n + 1):
f[i][j][k] = f[i - 1][j][k]
if j >= a and k >= b:
f[i][j][k] = max(f[i][j][k], f[i - 1][j - a][k - b] + 1)
return f[sz][m][n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for clear understanding of dynamic programming concepts.
- question_mark
Check for efficient space optimization techniques in DP.
- question_mark
Evaluate ability to break down a problem into manageable subproblems.
常见陷阱
外企场景- error
Overcomplicating the DP state transitions or failing to properly update the table.
- error
Ignoring the space complexity aspect and using an overly large DP table.
- error
Misunderstanding the problem constraints, especially in counting 0's and 1's.
进阶变体
外企场景- arrow_right_alt
Consider variations with additional constraints, like limiting the number of binary strings that can be selected.
- arrow_right_alt
Modify the problem by changing the allowed counts of 0's and 1's or adding more characters to the binary strings.
- arrow_right_alt
Test how the solution handles larger inputs and evaluate performance scalability.