代码随想录刷题day28

题目:复原ip地址
题解:

1)思考终止条件:将每一个子ip作为数组存在temp中。当子ip的个数达到4,而且切割位置到达最后一位(这里要注意:startIndex >= len(s),只有当startIndex达到不合法的时候才算切割完毕。
2)在判断合法性的时候,要注意0单独是合法的,但是‘023’这种0在数字之前就是不合法的。

代码:
class Solution(object):
    def restoreIpAddresses(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        res = []
        temp = []

        def isvalid(ip):
            if ip == '0':
                return True
            if int(ip) >= 0 and int(ip) <= 255:
                if ip[0] == '0':
                    return False
                return True

            
 
            
        def backtracking(s, startIndex):
            if len(s) > 12:
                return 
            if len(temp) == 4 and startIndex >= len(s):
                res.append(".".join(temp[:]))
            for i in range(startIndex, len(s)):
                tmp = s[startIndex : i + 1]
                if not isvalid(tmp):
                    continue
                temp.append(tmp)
                backtracking(s, i + 1)
                temp.pop()
            
        # if s == '0000':
        #     return ['0.0.0.0']
        backtracking(s, 0)
        return res
题目:子集
题解:

1)子集问题和组合、分割的区别在于:子集问题是求树的所有节点,而那两个问题是只求叶子节点。
2)注意要在判断startIndex是否遍历完之前,加入当前的节点。

代码:
class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        temp = []
        if not nums:
            return res
        def backtracking(nums, startIndex):
            res.append(temp[:])
            if startIndex >= len(nums):
                return
            
            for i in range(startIndex, len(nums)):
                temp.append(nums[i])
                backtracking(nums, i+ 1)
                temp.pop()
        backtracking(nums, 0)
        return res
题目:子集2
题解:

1)和组合2非常的像。重点在于:先将数组排序,再将树同层的、重复的元素剔除(用continue实现)

代码:
class Solution(object):
    def subsetsWithDup(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        temp = []
        nums.sort()
        if not nums:
            return res
        def backtracking(nums, startIndex):
   

            res.append(temp[:])
            if startIndex >= len(nums):
                return
            
            for i in range(startIndex, len(nums)):
                if i > startIndex and nums[i] == nums[i - 1]:
                    continue
                temp.append(nums[i])
                backtracking(nums, i+ 1)
                temp.pop()
        backtracking(nums, 0)
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值