131分割回文串
在代码里什么是切割线呢?
递归参数需要传入startIndex,表示下一轮递归遍历的起始位置,这个startIndex就是切割线。
class Solution:
def partition(self, s: str) -> List[List[str]]:
path = []
res = []
def is_parlindrome(s, start, end):
i = start
j = end
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
def backtracking(s, startindex):
if startindex == len(s):
res.append(path[:])
# 此次比其他组合题目多了一步判断:
# 判断被截取的这一段子串([start_index, i])是否为回文串
for i in range(startindex, len(s)):
# 判断同一层上以及截取的字符串是不是回文
if is_parlindrome(s, startindex, i):
path.append(s[startindex:i + 1])# 将startindex~i的字符串取出来
backtracking(s, i + 1) # 递归纵向遍历:从下一处进行切割,判断其余是否仍为回文串
path.pop()
# 不是回文 则换个切割位置
else:
continue
backtracking(s, 0)
return res
93.复原IP地址
怎么判断子串合法?
- 段位以0为开头的数字不合法
- 段位里有非正整数字符不合法
- 段位如果大于255了不合法
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
path = [] # 收集纵向分支路径上的字符
res = []# 存放最后的结果
def isvalid(subs):
if len(subs) > 1 and subs[0] == '0':
return False
if 0 <= int(subs) <=255:
return True
return False
def backtracking(s,startindex):
# 搜索路径大于4 剪枝
if len(path) > 4:
return
# 如果深度是4表示分成了4段 同时startindex 越界了说明到s的末尾 加入结果集
if len(path) == 4 and startindex == len(s):
res.append('.'.join(path))
return
for i in range(startindex,len(s)):
sub = s[startindex:i + 1]# 本层的子串
if isvalid(sub):
path.append(sub)
backtracking(s,i + 1)# 从i后一位开始递归
path.pop()
backtracking(s, 0)
return res