【LeetCode 刷题】回溯算法(2)-分割问题

此博客为《代码随想录》回溯算法章节的学习笔记,主要内容为回溯算法分割问题相关的题目解析。

131.分割回文串

题目链接

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        res, path = [], []

        def check(s: str) -> bool:
            left, right = 0, len(s) - 1 
            while left < right:
                if s[left] != s[right]:
                    return False
                left += 1
                right -= 1
            return True

        def dfs(start: int) -> None:
            if start == len(s):
                res.append(path.copy())
                return
            for i in range(start, len(s)):
                if check(s[start:i+1]):
                    path.append(s[start:i+1])
                    dfs(i + 1)
                    path.pop()
        
        dfs(0)
        return res
  • dfs 的参数为当前子串的起始位置,之后枚举子串的结束位置
  • 双指针法判断是否为回文串,也可直接使用 t == t[::-1] 判断

93.复原IP地址

题目链接

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        res, path = [], []

        def check(s: str) -> bool:
            if not s.isdigit():
                return False
            if len(s) > 1 and s[0] == '0':  # 含有前导零
                return False
            return 0 <= int(s) <= 255
        
        def dfs(start: int) -> None:
            if start == len(s) and len(path) == 4:
                res.append('.'.join(path))
                return
            if len(path) == 4:
                return
            for i in range(start, len(s)):
                if check(s[start:i+1]):
                    path.append(s[start:i+1])
                    dfs(i + 1)
                    path.pop()

        dfs(0)
        return res
  • 添加对分割次数的限制,即只能分割为四段
  • check() 函数的逻辑需根据题目要求编写,其他逻辑与上题的分割过程基本一致
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值