✅DAY24 回溯续 | 93.复原IP地址 | 78.子集 | 90.子集II

93. 复原 IP 地址

解题思路:模拟分割的每种情况,首先满足前导不为0,s中间不存在非数值,且每段取值区间在[0,255]

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        result = []
        self.backtracking(s, 0, 0, "", result)
        return result

    def backtracking(self, s, startIndex, pointNum, current, result):
        # 如果已经分割为 4 段,检查最后一段是否合法
        if pointNum == 3:
            if self.is_valid(s, startIndex, len(s) - 1):
                # 加入第四段并添加到结果中
                current += s[startIndex:]
                result.append(current)
            return

        # 从当前位置开始尝试分割
        for i in range(startIndex, len(s)):
            # 如果该段合法,则继续
            if self.is_valid(s, startIndex, i):
                sub = s[startIndex:i+1]  # 提取子字符串
                # 递归调用并增加分割点数量
                self.backtracking(s, i + 1, pointNum + 1, current + sub + ".", result)
            else:
                break  # 如果当前段不合法,退出循环

    def is_valid(self, s, start, end):
        # 检查是否超出范围或前导零
        if start > end:
            return False
        if s[start] == '0' and start != end:
            return False
        num = int(s[start:end + 1])
        return 0 <= num <= 255

78. 子集

解题思路:找出所有切割的可能性,本题没有重复元素

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        result = []
        path = []
        self.backtracking(nums, 0, path, result)
        return result
    
    def backtracking(self, nums, startIndex, path, result):
        result.append(path[:])
        for i in range(startIndex, len(nums)):
            path.append(nums[i])
            self.backtracking(nums, i+1, path, result)
            path.pop()

90. 子集 II

解题思路:有重复值,当遇到重复值值应当要跳过,避免造成重复解

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        path = []
        result = []
        nums.sort()
        self.backtracking(nums,0,path,result)
        return result
    def backtracking(self, nums, startIndex, path, result):
        result.append(path[:])
        for i in range(startIndex, len(nums)):
            if i > startIndex and nums[i] == nums[i-1]:
                continue
            path.append(nums[i])
            self.backtracking(nums, i+1, path,result)
            path.pop()
            

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值