算法题day29(补5.16日卡)

一、继续学习回溯算法:

1.leetcode题目 93. 复原 IP 地址 - 力扣(LeetCode)

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        path = []
        result = []
        def is_valid(s,start,end):
            if start>end:
                return False
            if s[start] == '0' and start != end:
                return False
            return  0<=int(s[start:end+1])<=255
            
        def dfs(path,result,s_index,s):
            if s_index == len(s) and len(path) == 4:
                result.append(".".join(path))
                return
            if len(path) > 4:
                return
            for i in range(s_index,min(s_index+3,len(s))):
                if is_valid(s,s_index,i):
                    sub = s[s_index:i+1]
                    path.append(sub)
                    dfs(path,result,i+1,s)
                    path.pop()
        dfs(path,result,0,s)
        return result

2.leetcode题目 78. 子集 - 力扣(LeetCode)

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

3.leetcode题目 90. 子集 II - 力扣(LeetCode)

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        path = []
        result = []
        def dfs(nums,path,result,s_index):
            result.append(path[:])
            for i in range(s_index,len(nums)):
                if i>s_index and nums[i] == nums[i-1]:  ##很关键,有重复元素时的处理操作
                    continue
                path.append(nums[i])
                dfs(nums,path,result,i+1)
                path.pop()
        nums.sort()
        dfs(nums,path,result,0)
        return result

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值