题目描述:Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
题目理解:
将一段字符str广度搜索截取,分别有n种组合形式,添加限制条件,过滤掉不适合的组合元素。 长度,大小,首字母
应用:如果进行字符串的子元素组合穷举,可以应用。
所有的for循环,利用到前一个状态,都可以理解为动态规划的一种分支
import copy
class Solution:
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
lens=[1,2,3]
combinations_all=[]
combinations_return=[]
def bfs(len_cur,s_cur,combinations_in):
for len_iter in lens:
combinations_in_copied=copy.deepcopy(combinations_in)
len_left_over=len_cur-len_iter
id_cur=s_cur[:len_iter]
if id_cur and int(id_cur)>255:
return
# print(id_cur)
# combinations_in.append(id_cur)
combinations_in_copied.append(id_cur)
if len(combinations_in_copied)<=4:
if len_left_over == 0 and len(combinations_in_copied)==4:
combinations_in_copied=list(filter(lambda x:not (len(x)>1 and x.startswith('0')),combinations_in_copied))
if len(combinations_in_copied)==4:
# print('combinations_in_copied==>',combinations_in_copied)
combinations_in_copied=[str(elem_iter) for elem_iter in combinations_in_copied]
elem='.'.join(combinations_in_copied)
combinations_return.append(elem)
# combinations_all.append(combinations_in_copied)
return
elif len_left_over<0:
return
else:
bfs(len_left_over,s_cur[len_iter:],combinations_in_copied)
else:
return
bfs(len(s),s,combinations_all)
# print(combinations_return)
return combinations_return