宁都县建设局网站,培训心得体会范文大全1000,怎么在境外做网站,创建公司网站 教程93.复原IP地址
思路#xff1a;
1.确定回溯函数参数#xff1a;定义全局遍历存放res集合和单个path#xff0c;还需要 s字符 startindex#xff08;int#xff09;为下一层for循环搜索的起始位置。
2.终止条件#xff1a;当len(path)4且遍历到字符串最末尾#xff…93.复原IP地址
思路
1.确定回溯函数参数定义全局遍历存放res集合和单个path还需要 s字符 startindexint为下一层for循环搜索的起始位置。
2.终止条件当len(path)4且遍历到字符串最末尾将path加入reslen(path)4 return
3.遍历过程取temp s[startindex:i1]判断是否合法
不能超过2550不能为前导 不能为00不能为非0数字前导e.g: 011
class Solution:def restoreIpAddresses(self, s: str) - List[str]:res []path []def backtrack(s,startindex):if len(path)4:return if len(path) 4 and startindex len(s):res.append(..join(path))return for i in range(startindex, len(s)):temp s[startindex:i1]if int(temp)255:continueif int(temp) 0 and i!startindex:continueif s[startindex]0and int(temp)0:continuepath.append(temp)backtrack(s,i1)path.pop()backtrack(s,0)return res78. 子集
思路:
1.确定回溯函数参数定义全局遍历存放res集合和单个path还需要
nums数组startindexint为下一层for循环搜索的起始位置。
2.终止条件当startindex len(nums)完成遍历终止
3.遍历过程求取子集问题不需要任何剪枝因为子集就是要遍历整棵树。
class Solution:def subsets(self, nums: List[int]) - List[List[int]]:res []path []def backtrack(nums,startindex):if startindexlen(nums):returnif len(path)len(nums):res.append(path[:])for i in range(startindex,len(nums)):path.append(nums[i])backtrack(nums,i1)path.pop()backtrack(nums,0)return res90. 子集 II
思路:
1.确定回溯函数参数定义全局遍历存放res集合和单个path还需要
nums数组startindexint为下一层for循环搜索的起始位置。
2.终止条件当startindex len(nums)完成遍历终止
3.遍历过程去重先对nums排序for循环层不能使用相同元素排序数组判断nums[i]nums[i-1]
class Solution:def subsetsWithDup(self, nums: List[int]) - List[List[int]]:res []path []nums.sort()def backtrack(nums,startindex):if startindexlen(nums):returnif len(path)len(nums):res.append(path[:])for i in range(startindex,len(nums)):if istartindex and nums[i] nums[i-1]:continuepath.append(nums[i])backtrack(nums,i1)path.pop()backtrack(nums,0)return res