标签:star dfs ip地址 style self idt output lazy nbsp
回溯法
思路:
dfs,深度优先搜索。
代码:
class Solution: def restoreIpAddresses(self, s: str) -> List[str]: def valid(segment): return int(segment) <= 255 if segment[0] != ‘0‘ else len(segment) == 1 def update_output(cur): segment = s[cur + 1:n] if valid(segment): path.append(segment) output.append(‘.‘.join(path)) path.pop() def backtrack(start = 0, dots = 3): for cur in range(start , min(n - 1, start + 3)): segment = s[start :cur + 1] if valid(segment): path.append(segment) if dots - 1 == 0: update_output(cur) else: backtrack(cur+1, dots - 1) path.pop() n = len(s) output, path = [], [] backtrack() return output
标签:star dfs ip地址 style self idt output lazy nbsp
原文地址:https://www.cnblogs.com/nilhxzcode/p/13165626.html