[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