1、思路
接上文思路,按理来说应该是先切割回文串,然后再去切割ip地址。有深入浅还是比较简单的,这个是手敲出来的哈哈哈
首先还是画图,画图回溯递归树,然后通过 横向for循环遍历回文串的len(s),再通过递归遍历深度。老样子,回溯三部曲:
1、递归条件:通过题意得知,当遍历当s的末尾的时候就可以处理当前字符串了。贴代码:
if startIndex == len(s)-1 {
res = append(res, path)
return
}
再就是for循环遍历横向遍历,再for循环第一层第一行逻辑处理单层遍历,然后递归深度,最后回溯整个过程:
for i := startIndex; i < len(s); i++ {
//处理单层逻辑
if IsPartitioned(s[startIndex : i+1]) {
path = append(path, s[startIndex:i+1])
}
backtracking(s, i+1, path)
path = path[:len(path)-1]
}
}
最后贴
package main
var res [][]string
func partition(s string) (res [][]string) {
start := 0
backtracking(s, start, []string{})
return
}
func backtracking(s string, startIndex int, path []string) {
if startIndex == len(s)-1 {
res = append(res, path)
return
}
for i := startIndex; i < len(s); i++ {
//处理单层逻辑
if IsPartitioned(s[startIndex : i+1]) {
path = append(path, s[startIndex:i+1])
}
backtracking(s, i+1, path)
path = path[:len(path)-1]
}
}
func IsPartitioned(s string) bool {
left, right := 0, len(s)-1
for left < right {
if s[left] != s[right] {
return false
}
left++
right++
}
return true
}
上完整代码,回文串的具体业务逻辑还是比较简单的,不再赘述,如果疑问,评论区和私信都可以,有问必答友友们。