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
}
相关推荐
蒟蒻小袁38 分钟前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先
GalaxyPokemon2 小时前
LeetCode - 148. 排序链表
linux·算法·leetcode
chao_7894 小时前
链表题解——环形链表 II【LeetCode】
数据结构·leetcode·链表
海奥华26 小时前
go中的接口返回设计思想
开发语言·后端·golang
岁忧7 小时前
LeetCode 高频 SQL 50 题(基础版)之 【高级字符串函数 / 正则表达式 / 子句】· 上
sql·算法·leetcode
eachin_z7 小时前
力扣刷题(第四十九天)
算法·leetcode·职场和发展
飞川撸码10 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
_Itachi__18 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
roman_日积跬步-终至千里18 小时前
【Go语言基础【14】】defer与异常处理(panic、recover)
golang