LeetCode 题解工作台
分割回文串
给你一个字符串 s ,请你将 s 分割成一些 子串 ,使每个子串都是 回文串 。返回 s 所有可能的分割方案。 示例 1: 输入: s = "aab" 输出: [["a","a","b"],["aa","b"]] 示例 2: 输入: s = "a" 输出: [["a"]] 提示: 1 s 仅由小写英…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们可以使用动态规划,预处理出字符串中的任意子串是否为回文串,即 表示子串 是否为回文串。 接下来,我们设计一个函数 ,表示从字符串的第 个字符开始,分割成若干回文串,当前分割方案为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个字符串 s,请你将 s 分割成一些 子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
示例 1:
输入:s = "aab" 输出:[["a","a","b"],["aa","b"]]
示例 2:
输入:s = "a" 输出:[["a"]]
提示:
1 <= s.length <= 16s仅由小写英文字母组成
解题思路
方法一:预处理 + DFS(回溯)
我们可以使用动态规划,预处理出字符串中的任意子串是否为回文串,即 表示子串 是否为回文串。
接下来,我们设计一个函数 ,表示从字符串的第 个字符开始,分割成若干回文串,当前分割方案为 。
如果 ,说明已经分割完成,我们将 放入答案数组中,然后返回。
否则,我们可以从 开始,从小到大依次枚举结束位置 ,如果 是回文串,那么就把 加入到 中,然后继续递归 ,回溯的时候要弹出 。
时间复杂度 ,空间复杂度 。其中 是字符串的长度。
class Solution:
def partition(self, s: str) -> List[List[str]]:
def dfs(i: int):
if i == n:
ans.append(t[:])
return
for j in range(i, n):
if f[i][j]:
t.append(s[i : j + 1])
dfs(j + 1)
t.pop()
n = len(s)
f = [[True] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
f[i][j] = s[i] == s[j] and f[i + 1][j - 1]
ans = []
t = []
dfs(0)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you understand how to use dynamic programming with backtracking in palindrome partitioning?
- question_mark
Can you efficiently identify palindromes and generate all partitions using state transitions?
- question_mark
Will you be able to optimize the solution with memoization to handle larger inputs?
常见陷阱
外企场景- error
Forgetting to check for palindrome substrings before adding them to partitions can result in incorrect outputs.
- error
Not using dynamic programming effectively to store intermediate results can lead to redundant computations, slowing down the solution.
- error
Failing to optimize the algorithm with memoization can cause performance issues for larger strings, especially with repeated checks.
进阶变体
外企场景- arrow_right_alt
Palindrome Partitioning II (min cuts): Find the minimum number of cuts needed for a palindrome partition.
- arrow_right_alt
Partition Strings into Palindromes (non-overlapping): Partition the string with no overlap and each substring being a palindrome.
- arrow_right_alt
Palindrome Partitioning III: Partition the string with the condition of maximizing the number of palindromic partitions.