回溯-切割问题:分割回文串/复原IP地址

131分割回文串

在这里插入图片描述

在这里插入图片描述

在代码里什么是切割线呢?
递归参数需要传入startIndex,表示下一轮递归遍历的起始位置,这个startIndex就是切割线。

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        path = []
        res = []
        def is_parlindrome(s, start, end):
            i = start
            j = end
            while i < j:
                if s[i] != s[j]:
                    return False
                i += 1
                j -= 1
            
            return True
         
        def backtracking(s, startindex):
            if startindex == len(s):
                res.append(path[:])
            # 此次比其他组合题目多了一步判断:
            # 判断被截取的这一段子串([start_index, i])是否为回文串
            for i in range(startindex, len(s)):
                # 判断同一层上以及截取的字符串是不是回文
                if is_parlindrome(s, startindex, i):
                    path.append(s[startindex:i + 1])# 将startindex~i的字符串取出来
                    backtracking(s, i + 1) # 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
                    path.pop()
                # 不是回文 则换个切割位置
                else:
                    continue
        
        backtracking(s, 0)
        return res

93.复原IP地址

怎么判断子串合法?

  • 段位以0为开头的数字不合法
  • 段位里有非正整数字符不合法
  • 段位如果大于255了不合法
    在这里插入图片描述
class Solution(object):
    def restoreIpAddresses(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        path = [] # 收集纵向分支路径上的字符
        res = []# 存放最后的结果
        def isvalid(subs):
            if len(subs) > 1 and subs[0] == '0':
                return False
            if 0 <= int(subs) <=255:
                return True
            return False
        
        def backtracking(s,startindex):
            # 搜索路径大于4 剪枝
            if len(path) > 4:
                return 
            # 如果深度是4表示分成了4段 同时startindex 越界了说明到s的末尾 加入结果集
            if len(path) == 4 and startindex == len(s):
                res.append('.'.join(path))
                return

            for i in range(startindex,len(s)):
                sub = s[startindex:i + 1]# 本层的子串
                if isvalid(sub):
                    path.append(sub)
                    backtracking(s,i + 1)# 从i后一位开始递归
                    path.pop()

        backtracking(s, 0)
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值