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
// @Title: 分割回文串 (Palindrome Partitioning)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 12 ms
// @Memory: 5.1 MB
func partition(s string) [][]string {
    res := make([][]string, 0)
    cur := make([]string,0,len(s))
    dfs(s,0,cur,&res)
    return res
}

func dfs(s string, i int, cur []string, res *[][]string) {
    if len(s) == i {
        tmp := make([]string, len(cur))
        copy(tmp, cur)
        *res = append(*res, tmp)
        return 
    }
    
    for j:=i;j<len(s);j++ {
        if isPalindrome(s[i:j+1]) {
            dfs(s,j+1,append(cur,s[i:j+1]),res)
        }
    }
}

func isPalindrome(s string) bool {
    slen := len(s)-1
    for i,j :=0, slen;i<j;i,j=i+1,j-1 {
        if s[i] != s[j] {
            return false
        }
    }
    return true
}