给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文。
返回符合要求的 最少分割次数 。
示例 1:
输入:s = "aab"
输出:1
解释:只需一次分割就可将 s 分割成 ["aa","b"] 这样两个回文子串。
示例 2:
输入:s = "a"
输出:0
示例 3:
输入:s = "ab"
输出:1
提示:
1 <= s.length <= 2000
s 仅由小写英文字母组成
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-partitioning-ii
参考:
# 0132.分割回文串II class Solution: def minCut(self, s: str) -> int: """ 动态规划 :param s: :return: """ length = len(s) dp = [[True] * length for _ in range(length)] for i in range(length-1, -1, -1): for j in range(i+1, length): dp[i][j] = (s[i]==s[j]) and dp[i+1][j-1] f = [float("INF")] * length for i in range(length): if dp[0][i]: f[i] = 0 else: for j in range(i): if dp[j+1][i]: f[i] = min(f[i], f[j]+1) return f[length-1] def minCut_(self, s: str) -> int: """ 参考题131, 回溯法超时间 :param s: :return: """ res = [] path = [] def isPalindrome(s): n = len(s) i, j = 0, n - 1 while i < j: if s[i] != s[j]: return False i += 1 j -= 1 return True def track(s, startIndex): # 起始位置已经大于s的大小,说明已经找到一组分割方案 if startIndex >= len(s): res.append(path[:]) return for i in range(startIndex, len(s)): # 获取[startIndex:i+1]的子串 p = s[startIndex:i + 1] if isPalindrome(p): path.append(p) else: continue track(s, i + 1) path.pop() # 回溯 track(s, 0) MIN = 10000 for item in res: length = len(item) MIN = min(MIN, length-1) return MIN
待完善