Skip to content

93. Restore IP Addresses

题目

A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.

  • For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses.

Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.

 

Example 1:

Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]

Example 2:

Input: s = "0000"
Output: ["0.0.0.0"]

Example 3:

Input: s = "101023"
Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

 

Constraints:

  • 1 <= s.length <= 20
  • s consists of digits only.
Related Topics
  • 字符串
  • 回溯

  • 👍 1522
  • 👎 0
  • 思路

    回溯的关键判断条件是,每一位选择 1-3 位数,而非一位一位的去遍历 同时注意剪枝叶条件

    解法

    py
    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution:
        def restoreIpAddresses(self, s: str) -> List[str]:
            res = []
    
            def backtrack(start, path):
                if len(path) == 4:
                    if start == len(s):
                        res.append('.'.join(path))
                    return
    
                for i in range(1, 4):
                    if start + i > len(s): break
                    segement = s[start :  start + i]
    
                    if isValidIP(segement):
                        path.append(segement)
                        backtrack(start + i, path)
                        path.pop()
                    else:
                        break
    
            def isValidIP(segement: str):
                if segement[0] == '0':
                    return True if len(segement) == 1 else False
    
                if 0 <= int(segement) <= 255:
                    return True
    
                return False
    
            backtrack(0, [])
            return res
    
            
    # leetcode submit region end(Prohibit modification and deletion)

    复杂度分析

    • 时间复杂度 O(1)
    • 空间复杂度 O(K)
      • k = valid Ip