1 Star 0 Fork 0

catyMap / AlgorithmNote

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
partition2.go 979 Bytes
一键复制 编辑 原始数据 按行查看 历史
dogemap 提交于 2021-03-30 22:11 . 未归类算法题目提交
package main
import (
"fmt"
"math"
)
func partition(s string) int {
n := len(s)
if n == 0 || n == 1 {
return 0
}
mem := make(map[int]map[int]int)
for i := 0 ; i < n ; i ++ {
mem[i] = make(map[int]int)
}
res := make([][]string,0,0)
var backTrace func (l ,r int , str string, tmp []string)
backTrace = func(l, r int, str string ,tmp []string) {
if l == r {
res = append(res, tmp)
}
for i := l + 1 ; i <= r ; i ++ {
sub := str[l:i]
if mem[l][i] == 1 || IsPalindrome(sub){
mem[l][i] = 1
tmp = append(tmp, sub)
backTrace(i ,r ,str , append([]string{} , tmp...))
tmp = tmp[:len(tmp)-1]
continue
}
}
}
backTrace(0,n,s,[]string{})
times := math.MaxInt32
for _ , a := range res {
times = min(times , len(a))
}
return times - 1
}
func IsPalindrome (s string) bool {
n := len(s)
for i := 0 ; i < n / 2 ; i++ {
if s[i] != s[n-i-1] {
return false
}
}
return true
}
func main() {
fmt.Println(partition("aab"))
}
Go
1
https://gitee.com/dogemap/algorithm-note.git
git@gitee.com:dogemap/algorithm-note.git
dogemap
algorithm-note
AlgorithmNote
dc486f96f6c1

搜索帮助