leetcode 每日一题 93. 复原IP地址
回溯法
思路:
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