LeetCode 题解工作台
删列造序 III
给定由 n 个小写字母字符串组成的数组 strs ,其中每个字符串长度相等。 选取一个删除索引序列,对于 strs 中的每个字符串,删除对应每个索引处的字符。 比如,有 strs = ["abcdef","uvwxyz"] ,删除索引序列 {0, 2, 3} ,删除后为 ["bef", "vyz"]…
3
题型
6
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
我们定义 表示以第 列结尾的最长不下降子序列的长度,初始时 $f[i] = 1$,答案即为 $n - \max(f)$。 考虑计算 ,我们可以枚举 $j < i$,如果对于所有的字符串 ,有 $s[j] \le s[i]$,那么 $f[i] = \max(f[i], f[j] + 1)$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定由 n 个小写字母字符串组成的数组 strs ,其中每个字符串长度相等。
选取一个删除索引序列,对于 strs 中的每个字符串,删除对应每个索引处的字符。
比如,有 strs = ["abcdef","uvwxyz"] ,删除索引序列 {0, 2, 3} ,删除后为 ["bef", "vyz"] 。
假设,我们选择了一组删除索引 answer ,那么在执行删除操作之后,最终得到的数组的行中的 每个元素 都是按字典序排列的(即 (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]) 和 (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]) ,依此类推)。
请返回 answer.length 的最小可能值 。
示例 1:
输入:strs = ["babca","bbazb"] 输出:3 解释: 删除 0、1 和 4 这三列后,最终得到的数组是 strs = ["bc", "az"]。 这两行是分别按字典序排列的(即,strs[0][0] <= strs[0][1] 且 strs[1][0] <= strs[1][1])。 注意,strs[0] > strs[1] —— 数组 strs 不一定是按字典序排列的。
示例 2:
输入:strs = ["edcba"] 输出:4 解释:如果删除的列少于 4 列,则剩下的行都不会按字典序排列。
示例 3:
输入:strs = ["ghi","def","abc"] 输出:0 解释:所有行都已按字典序排列。
提示:
n == strs.length1 <= n <= 1001 <= strs[i].length <= 100strs[i]由小写英文字母组成
解题思路
方法一:动态规划
我们定义 表示以第 列结尾的最长不下降子序列的长度,初始时 ,答案即为 。
考虑计算 ,我们可以枚举 ,如果对于所有的字符串 ,有 ,那么 。
最后,我们返回 。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 每个字符串的长度和数组的长度。
class Solution:
def minDeletionSize(self, strs: List[str]) -> int:
n = len(strs[0])
f = [1] * n
for i in range(n):
for j in range(i):
if all(s[j] <= s[i] for s in strs):
f[i] = max(f[i], f[j] + 1)
return n - max(f)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N * W^2) |
| 空间 | O(W) |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates understanding of dynamic programming by breaking down the problem into subproblems.
- question_mark
The candidate applies state transition logic in the context of lexicographical order for string arrays.
- question_mark
The candidate shows the ability to optimize deletions by evaluating column states.
常见陷阱
外企场景- error
Overcomplicating the deletion strategy by considering unnecessary combinations of deletions.
- error
Neglecting to consider lexicographical order while transitioning between states in dynamic programming.
- error
Failing to properly implement the dynamic programming table, resulting in incorrect deletions or missing steps.
进阶变体
外企场景- arrow_right_alt
Adjust the problem to allow deletions based on other constraints, such as length or character range.
- arrow_right_alt
Extend the problem to consider lexicographical sorting within different subsets of strings.
- arrow_right_alt
Explore the possibility of finding a generalized solution for sorting arrays of arbitrary objects under different sorting rules.