u
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
package top100liked
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// https://leetcode.cn/problems/palindrome-partitioning/description/?envType=study-plan-v2&envId=top-100-liked
|
||||
|
||||
func partition(s string) [][]string {
|
||||
res := [][]string{}
|
||||
path := []string{}
|
||||
// 动态规划,降低查找回文串的时间复杂度
|
||||
dp := make([][]bool, len(s))
|
||||
for i := range len(s) {
|
||||
dp[i] = make([]bool, len(s))
|
||||
dp[i][i] = true
|
||||
}
|
||||
for length := 2; length <= len(s); length++ {
|
||||
for i := 0; i+length <= len(s); i++ {
|
||||
j := i + length - 1
|
||||
dp[i][j] = (s[i] == s[j]) && (length <= 2 || dp[i+1][j-1])
|
||||
}
|
||||
}
|
||||
|
||||
var helper func(start int)
|
||||
helper = func(start int) {
|
||||
if start == len(s) {
|
||||
cp := make([]string, len(path))
|
||||
copy(cp, path)
|
||||
res = append(res, cp)
|
||||
return
|
||||
}
|
||||
for end := start; end < len(s); end++ {
|
||||
if dp[start][end] {
|
||||
path = append(path, s[start:end+1])
|
||||
helper(end + 1)
|
||||
path = path[:len(path)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
helper(0)
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func Test(t *testing.T) {
|
||||
fmt.Printf("%+v\n", partition("aab"))
|
||||
}
|
||||
|
||||
func Test2(t *testing.T) {
|
||||
fmt.Printf("%+v\n", partition("a"))
|
||||
}
|
||||
Reference in New Issue
Block a user