forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1278.go
43 lines (41 loc) · 927 Bytes
/
1278.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
func palindromePartition(s string, k int) int {
n := len(s)
p := make([][]int, n)
for i := 0; i < n; i++ {
p[i] = make([]int, n)
}
for j := 1; j < n; j++ {
for i := j - 1; i >= 0; i-- {
if s[i] != s[j] {
p[i][j] = 1
}
if i + 1 < j {
p[i][j] += p[i + 1][j - 1]
}
}
}
f := make([][]int, k + 1)
for i := 0; i <= k; i++ {
f[i] = make([]int, n)
for j := 0; j < n; j++ {
f[i][j] = 100
}
}
for i := 0; i < n; i++ {
f[1][i] = p[0][i]
}
for i := 2; i <= k; i++ {
for r := i - 1; r < n; r++ {
for l := i - 2; l < r; l++ {
f[i][r] = min(f[i][r], f[i-1][l] + p[l+1][r])
}
}
}
return f[k][n-1]
}
func min(a, b int) int {
if a < b {
return a
}
return b
}