属于切分问题 需要一个start
注意判断:起始≠0 数字范围
数字最多3位 提前剪枝
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
res=[]
self.back(s,0,[],res)
return res
def back(self,s,idx,path,res):
if len(path)==4 and idx==len(s):
res.append('.'.join(path))
return
if len(path)>4:
return
for i in range(idx,min(idx+3,len(s))):
if self.isvalid(s,idx,i):
path.append(s[idx:i+1])
self.back(s,i+1,path,res)
path.pop()
def isvalid(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]]:
res=[]
self.back(nums,0,[],res)
return res
def back(self,nums,start,path,res):
res.append(path[:])
for i in range(start,len(nums)):
path.append(nums[i])
self.back(nums,i+1,path,res)
path.pop()
排序后 有连号的就跳过
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
res=[]
nums.sort()
self.back(nums,0,[],res)
return res
def back(self,nums,start,path,res):
res.append(path[:])
for i in range(start,len(nums)):
if i>start and nums[i]==nums[i-1]:
continue
path.append(nums[i])
self.back(nums,i+1,path,res)
path.pop()