【leetcode系列】【算法】【中等】复原IP地址

题目:

题目链接: https://leetcode-cn.com/problems/restore-ip-addresses/

解题思路:

"所有可能" = 回溯 + 剪枝

剪枝条件为:

  1. 如果已遍历完,则判断是否合法

  2. 如果当前已有4位ip,但是字符串未遍历完

  3. 如果当前位置字符串长度大于1,并且第一位字符是'0'

代码实现:

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        def create_res(start, s, res, path):
            if start >= len(s):
                if 4 == len(path):
                    res.append('.'.join(path))
                return
            elif 4 <= len(path):
                return
            
            for index in range(1, 4):
                if start + index > len(s):
                    break
                    
                curr_str = s[start:start + index]
                int_val = int(curr_str)
                if int_val < 0 or int_val > 255:
                    continue
                elif 1 < len(curr_str) and '0' == curr_str[0]:
                    break
                    
                path.append(curr_str)
                create_res(start + index, s, res, path)
                path.pop()

        if 12 < len(s):
            return []
        
        res = []
        create_res(0, s, res, [])
        return res
发布了100 篇原创文章 · 获赞 4 · 访问量 1468

猜你喜欢

转载自blog.csdn.net/songyuwen0808/article/details/105319760
今日推荐