回溯切割131:IsPartitioned

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
}

上完整代码,回文串的具体业务逻辑还是比较简单的,不再赘述,如果疑问,评论区和私信都可以,有问必答友友们。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值