@@ -527,6 +527,7 @@ class Solution:
527527
528528```
529529### Go
530+ 回溯 基本版
530531``` go
531532var (
532533 path []string // 放已经回文的子串
@@ -565,6 +566,63 @@ func isPalindrome(s string) bool {
565566}
566567```
567568
569+ 回溯+动态规划优化回文串判断
570+ ``` go
571+ var (
572+ result [][]string
573+ path []string // 放已经回文的子串
574+ isPalindrome [][]bool // 放事先计算好的是否回文子串的结果
575+ )
576+
577+ func partition (s string ) [][]string {
578+ result = make ([][]string , 0 )
579+ path = make ([]string , 0 )
580+ computePalindrome (s)
581+ backtracing (s, 0 )
582+ return result
583+ }
584+
585+ func backtracing (s string , startIndex int ) {
586+ // 如果起始位置已经大于s的大小,说明已经找到了一组分割方案了
587+ if startIndex >= len (s) {
588+ tmp := make ([]string , len (path))
589+ copy (tmp, path)
590+ result = append (result, tmp)
591+ return
592+ }
593+ for i := startIndex; i < len (s); i++ {
594+ if isPalindrome[startIndex][i] { // 是回文子串
595+ // 获取[startIndex,i]在s中的子串
596+ path = append (path, s[startIndex:i+1 ])
597+ } else { // 不是回文,跳过
598+ continue
599+ }
600+ backtracing (s, i + 1 ) // 寻找i+1为起始位置的子串
601+ path = path[:len (path)-1 ] // 回溯过程,弹出本次已经添加的子串
602+ }
603+ }
604+
605+ func computePalindrome (s string ) {
606+ // isPalindrome[i][j] 代表 s[i:j](双边包括)是否是回文字串
607+ isPalindrome = make ([][]bool , len (s))
608+ for i := 0 ; i < len (isPalindrome); i++ {
609+ isPalindrome[i] = make ([]bool , len (s))
610+ }
611+ for i := len (s)-1 ; i >= 0 ; i-- {
612+ // 需要倒序计算, 保证在i行时, i+1行已经计算好了
613+ for j := i; j < len (s); j++ {
614+ if j == i {
615+ isPalindrome[i][j] = true
616+ } else if j - i == 1 {
617+ isPalindrome[i][j] = s[i] == s[j]
618+ } else {
619+ isPalindrome[i][j] = s[i] == s[j] && isPalindrome[i+1 ][j-1 ]
620+ }
621+ }
622+ }
623+ }
624+ ```
625+
568626### JavaScript
569627
570628``` js
0 commit comments