简繁EN

LeetCodeNo. 076

[LeetCode with Python] 93. Restore IP Addresses

Contents

Problem

Problem page: https://leetcode.com/problems/restore-ip-addresses/
Topics: Backtracking, String
Difficulty: Medium

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)


Analysis

(Could I solve this one with DP???)
Search, recursion, pruning.
The pruning conditions are: 1. No field can have a value greater than 255; 2. There must be exactly 4 fields; 3. A field with length >=2 can't start with 0. So the logic goes like this:

  1. If the current character isn't the last one
    1. If appending the current character to the current field (num) would give a value no greater than 255
      1. If the number of dots so far (fields) is less than 3, I can try adding a dot to the prefix (prefix) and starting a new field with the current character
      2. If the current field isn't 0, I can try appending the character to it
        2 Otherwise, check whether there are fewer than 3 dots so far. If so, I can try adding a dot to the prefix (prefix) and starting a new field with the current character
    2. Otherwise, this branch fails
  2. If the current character is the last one
    1. If there are already three dots, the current field isn't 0, and appending the current character would give a value no greater than 255, I can try appending it
    2. Otherwise, if there are already two dots, end the current field with a dot and use the current character as the last field to get a solution
    3. Otherwise, this branch fails

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:

def doRestoreIpAddresses(self, prefix, num, s, start, fields):
if start == len(s) - 1:
results1 = [ ]
results2 = [ ]
if int(num + s[start]) <= 255 and 3 == fields and '0' != num:
results1 = [prefix + s[start]]
elif 2 == fields:
results2 = [prefix + '.' + s[start]]
return results1 + results2
if int(num + s[start]) <= 255:
results0 = [ ]
results1 = [ ]
if fields < 3:
results0 = self.doRestoreIpAddresses(prefix + '.' + s[start], s[start], s, start + 1, fields + 1)
if '0' != num:
results1 = self.doRestoreIpAddresses(prefix + s[start], num + s[start], s, start + 1, fields)
return results0 + results1
elif fields < 3:
results0 = self.doRestoreIpAddresses(prefix + '.' + s[start], s[start], s, start + 1, fields + 1)
return results0
else:
return [ ]

# @param s, a string
# @return a list of strings
def restoreIpAddresses(self, s):
if len(s) < 4:
return [ ]
return self.doRestoreIpAddresses(s[0], s[0], s, 1, 0)

Article link: https://xnerv.wang/en/leetcode-restore-ip-addresses/