From 2d92b509e0689ce90e4460578de9772a459d3092 Mon Sep 17 00:00:00 2001 From: keepgogogo <57135073+keepgogogo@users.noreply.github.com> Date: Sun, 17 Dec 2023 14:00:00 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9B=9E=E6=BA=AF=E7=AE=97=E6=B3=95=E7=AF=87?= =?UTF-8?q?=209=20=E5=88=86=E5=89=B2=E5=9B=9E=E6=96=87=E4=B8=B2=EF=BC=8CJa?= =?UTF-8?q?va=E9=A2=98=E8=A7=A3=E7=A4=BA=E4=BE=8B=E4=BB=A3=E7=A0=81?= =?UTF-8?q?=E6=8F=90=E4=BE=9B=E4=BD=BF=E7=94=A8=E5=8A=A8=E6=80=81=E8=A7=84?= =?UTF-8?q?=E5=88=92=E4=BC=98=E5=8C=96=E5=9B=9E=E6=96=87=E4=B8=B2=E5=88=A4?= =?UTF-8?q?=E6=96=AD=E7=9A=84=E5=AE=9E=E7=8E=B0=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0131.分割回文串.md | 59 ++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/problems/0131.分割回文串.md b/problems/0131.分割回文串.md index 1d230ca8..ca342d4b 100644 --- a/problems/0131.分割回文串.md +++ b/problems/0131.分割回文串.md @@ -349,6 +349,65 @@ class Solution { } ``` +### Java +回溯+动态规划优化回文串判断 +```Java +class Solution { + List> result; + LinkedList path; + boolean[][] dp; + + public List> partition(String s) { + result = new ArrayList<>(); + char[] str = s.toCharArray(); + path = new LinkedList<>(); + dp = new boolean[str.length + 1][str.length + 1]; + isPalindrome(str); + backtracking(s, 0); + return result; + } + + public void backtracking(String str, int startIndex) { + if (startIndex >= str.length()) { + //如果起始位置大于s的大小,说明找到了一组分割方案 + result.add(new ArrayList<>(path)); + } else { + for (int i = startIndex; i < str.length(); ++i) { + if (dp[startIndex][i]) { + //是回文子串,进入下一步递归 + //先将当前子串保存入path + path.addLast(str.substring(startIndex, i + 1)); + //起始位置后移,保证不重复 + backtracking(str, i + 1); + path.pollLast(); + } else { + //不是回文子串,跳过 + continue; + } + } + } + } + + //通过动态规划判断是否是回文串,参考动态规划篇 52 回文子串 + public void isPalindrome(char[] str) { + for (int i = 0; i <= str.length; ++i) { + dp[i][i] = true; + } + for (int i = 1; i < str.length; ++i) { + for (int j = i; j >= 0; --j) { + if (str[j] == str[i]) { + if (i - j <= 1) { + dp[j][i] = true; + } else if (dp[j + 1][i - 1]) { + dp[j][i] = true; + } + } + } + } + } +} +``` + ### Python 回溯 基本版 ```python