[Leetcode Series] [] [medium] recovery algorithm IP address

topic:

Topic links:  https://leetcode-cn.com/problems/restore-ip-addresses/

 

Problem-solving ideas:

"All possible" = + prune back

Pruning conditions:

  1. If you have been traversed, it is determined whether or not legitimate

  2. If you currently have 4 ip, but the string is not complete traversal

  3. If the current position of a character string length is greater than 1, and is a '0'

 

Code:

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

 

Published 100 original articles · won praise 4 · Views 1468

Guess you like

Origin blog.csdn.net/songyuwen0808/article/details/105319760
Recommended