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 

 

posted @ 2020-06-19 19:07  nil_f  阅读(147)  评论(0编辑  收藏  举报