목차

Restore IP Addresses

ps
링크leetcode.com/…
출처LeetCode
문제 번호93
문제명Restore IP Addresses
레벨Medium
분류

완전탐색

시간복잡도O(1)
사용한 언어Python
제출기록24 ms / 14.3 MB
최고기록16ms
해결날짜2020/11/26

풀이

코드

"""Solution code for "LeetCode 93. Restore IP Addresses". (Non-recursive
version)

- Problem link: https://leetcode.com/problems/restore-ip-addresses/
- Solution link: http://www.teferi.net/ps/problems/leetcode/93
"""


import itertools


class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        ip_list = []
        for lengths in itertools.product([1, 2, 3], repeat=4):
            if sum(lengths) != len(s):
                continue
            numbers = []
            beg = 0
            for l in lengths:
                number = s[beg:beg + l]
                if (number[0] == '0' and l > 1) or int(number) > 255:
                    break
                numbers.append(number)
                beg += l
            else:
                ip_list.append('.'.join(numbers))

        return ip_list

"""Solution code for "LeetCode 93. Restore IP Addresses".

- Problem link: https://leetcode.com/problems/restore-ip-addresses/
- Solution link: http://www.teferi.net/ps/problems/leetcode/93
"""


class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        def solveRec(numbers, s):
            if len(numbers) == 4:
                if not s:
                    ip_list.append('.'.join(numbers))
                return

            for l in range(1, 4):
                if l > len(s):
                    break
                number = s[:l]
                if int(number) <= 255:
                    solveRec(numbers + [number], s[l:])
                if s[0] == '0':
                    break

        ip_list = []
        solveRec([], s)
        return ip_list