131.分割回文串增加Go动态规划优化回文串解法

This commit is contained in:
markwang
2024-07-25 10:36:23 +08:00
parent 8b0d5b234f
commit 3e6dc44fa1

View File

@ -527,6 +527,7 @@ class Solution:
```
### Go
回溯 基本版
```go
var (
path []string // 放已经回文的子串
@ -565,6 +566,63 @@ func isPalindrome(s string) bool {
}
```
回溯+动态规划优化回文串判断
```go
var (
result [][]string
path []string // 放已经回文的子串
isPalindrome [][]bool // 放事先计算好的是否回文子串的结果
)
func partition(s string) [][]string {
result = make([][]string, 0)
path = make([]string, 0)
computePalindrome(s)
backtracing(s, 0)
return result
}
func backtracing(s string, startIndex int) {
// 如果起始位置已经大于s的大小说明已经找到了一组分割方案了
if startIndex >= len(s) {
tmp := make([]string, len(path))
copy(tmp, path)
result = append(result, tmp)
return
}
for i := startIndex; i < len(s); i++ {
if isPalindrome[startIndex][i] { // 是回文子串
// 获取[startIndex,i]在s中的子串
path = append(path, s[startIndex:i+1])
} else { // 不是回文,跳过
continue
}
backtracing(s, i + 1) // 寻找i+1为起始位置的子串
path = path[:len(path)-1] // 回溯过程,弹出本次已经添加的子串
}
}
func computePalindrome(s string) {
// isPalindrome[i][j] 代表 s[i:j](双边包括)是否是回文字串
isPalindrome = make([][]bool, len(s))
for i := 0; i < len(isPalindrome); i++ {
isPalindrome[i] = make([]bool, len(s))
}
for i := len(s)-1; i >= 0; i-- {
// 需要倒序计算, 保证在i行时, i+1行已经计算好了
for j := i; j < len(s); j++ {
if j == i {
isPalindrome[i][j] = true
} else if j - i == 1 {
isPalindrome[i][j] = s[i] == s[j]
} else {
isPalindrome[i][j] = s[i] == s[j] && isPalindrome[i+1][j-1]
}
}
}
}
```
### JavaScript
```js