Golang | Leetcode Golang题解之第131题分割回文串

题目:

题解:

Go 复制代码
func partition(s string) (ans [][]string) {
    n := len(s)
    f := make([][]int8, n)
    for i := range f {
        f[i] = make([]int8, n)
    }

    // 0 表示尚未搜索,1 表示是回文串,-1 表示不是回文串
    var isPalindrome func(i, j int) int8
    isPalindrome = func(i, j int) int8 {
        if i >= j {
            return 1
        }
        if f[i][j] != 0 {
            return f[i][j]
        }
        f[i][j] = -1
        if s[i] == s[j] {
            f[i][j] = isPalindrome(i+1, j-1)
        }
        return f[i][j]
    }

    splits := []string{}
    var dfs func(int)
    dfs = func(i int) {
        if i == n {
            ans = append(ans, append([]string(nil), splits...))
            return
        }
        for j := i; j < n; j++ {
            if isPalindrome(i, j) > 0 {
                splits = append(splits, s[i:j+1])
                dfs(j + 1)
                splits = splits[:len(splits)-1]
            }
        }
    }
    dfs(0)
    return
}
相关推荐
Pniubi4 小时前
力扣76.最小覆盖子串
算法·leetcode·职场和发展
文丑颜不良啊10 小时前
LeetCode2541~2560题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2481~2500题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2461~2480题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2441~2460题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2521~2540题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2501~2520题目解析
java·leetcode
Pniubi2 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
利威尔xu2 天前
Go map 底层崩溃:3 个 goroutine 并发写同一张 map,fatal error 崩掉整个服务
golang·源码·map·并发·后端开发
Rain的Java大神之路2 天前
LeetCode 37 解数独面试攻略:回溯 + 位掩码 + MRV,从暴力到毫秒级求解
java·后端·leetcode