【代码随想录算法训练营】第28天 | 第七章 回溯(四)

主要内容

  1. 子集,组合,排序,去重
  2. 分割

题目

93.复原IP地址

思路分析

分割

代码

# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
    # 字符串的分割
    def __init__(self):
        self.res = []
        self.path = []
    def restoreIpAddresses(self, s: str) -> List[str]:
        self.backtracking(s, 0)
        return self.res

    def backtracking(self, s, startindex):
        if startindex >= len(s) and len(self.path) >= 4:
            if startindex == len(s) and len(self.path) == 4:
                self.res.append(".".join(self.path))
            return

        for i in range(startindex, len(s)):
            temp = s[startindex:i+1]
            # 判断c是否满足,前导0,且值在[0,255]之间
            if len(str(int(temp))) == len(temp) and int(temp) >= 0 and int(temp) <= 255:
                self.path.append(temp)
                self.backtracking(s, i + 1)
                self.path.pop()
            else:
                continue
# leetcode submit region end(Prohibit modification and deletion)

78.子集

思路分析

先收集结果

代码

# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
    def __init__(self):
        self.res = []
        self.path = []

    def subsets(self, nums: List[int]) -> List[List[int]]:
        self.backtracking(nums, 0)
        return self.res

    def backtracking(self, nums, startindex):
        # 收集结果
        self.res.append(self.path[:])
        # 终止条件,可省略
        if startindex >= len(nums):
            return
        for i in range(startindex, len(nums)):
            self.path.append(nums[i])
            self.backtracking(nums, i+1)
            self.path.pop()

# leetcode submit region end(Prohibit modification and deletion)

90.子集II

思路分析

  1. 先收集结果
  2. 排序去重

代码

# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
    def __init__(self):
        self.res = []
        self.path = []
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        self.backtracking(sorted(nums),0)
        return self.res


    def backtracking(self, nums, startindex):
        self.res.append(self.path[:])
        if startindex >= len(nums):
            return
        for i in range(startindex, len(nums)):
            if i > startindex and nums[i] == nums[i-1]:
                continue
            self.path.append(nums[i])
            self.backtracking(nums, i+1)
            self.path.pop()

# leetcode submit region end(Prohibit modification and deletion)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值