题目描述
原题链接:93. 复原 IP 地址
解题思路
本题是分割问题,思路与131. 分割回文串(分割问题)类似,不同之处在于分割的判定条件和分割方式。
回溯三部曲:
(1)递归参数:
vector<string> res;
bool isValidIP(string s, int start, int end);
void backtracking(string s, int startIndex, int dotNum);
使用res
存储结果。
isValidIP
中start
和end
为判定的IP位下标。
backtracking
中startIndex
为下一次遍历起始下标,dotNum
为记录已经点取的小数点个数。
(2)终止条件:
if(dotNum == 3) {
// 判定是否为有效划分IP方式
if(isValidIP(s, startIndex, s.size() - 1)) {
res.push_back(s);
}
return ;
}
点够三个点,若全部为有效IP,则加入结果集,否则跳过。
(3)单层搜索逻辑:
// 划分IP地址
for(int i = startIndex; i < s.size(); i++) {
if(isValidIP(s, startIndex, i)) {
dotNum++;
s.insert(s.begin() + i + 1, '.'); // 从i+1之前点上小数点
backtracking(s, i + 2, dotNum); // 已加入一个字符,一次从加2开始遍历
s.erase(s.begin() + i + 1); // 移除点的小数点,进行回溯
dotNum--;
} else {
break; // 只要有一个不合法,直接跳出循环
}
}
从s
中依次选取IP位来划分,使用isValidIP
来判定划分的这段是否位有效IP。s.insert(x, '.')
函数是在x
之前插入’.',因此传入为i + 1
。因为,s
的长度增一,因此下次选择路径需从i + 2
开始。回退时,再删除.
。
class Solution {
public:
vector<string> res;
bool isValidIP(string s, int start, int end) {
// 去除第三个小数点在最后的情况
if(start >= s.size()) return false;
// 当为多位数时,若开头位0,则返回false
if(start != end && s[start] == '0') return false;
// 当为三位数时(0为起始下标,所以差值为2),若大于255,则返回false
if(end - start == 2) {
int x = (s[start] - '0') * 100 + (s[start + 1] - '0') * 10 + (s[end] - '0');
if(x > 255) return false;
// 超过三位数,直接返回false
} else if(end - start > 2) {
return false;
}
return true;
}
void backtracking(string s, int startIndex, int dotNum) {
// 已点够三个小数点
if(dotNum == 3) {
// 判定是否为有效划分IP方式
if(isValidIP(s, startIndex, s.size() - 1)) {
res.push_back(s);
}
return ;
}
// 划分IP地址
for(int i = startIndex; i < s.size(); i++) {
if(isValidIP(s, startIndex, i)) {
dotNum++;
s.insert(s.begin() + i + 1, '.'); // 从i+1之前点上小数点
backtracking(s, i + 2, dotNum); // 已加入一个字符,一次从加2开始遍历
s.erase(s.begin() + i + 1); // 移除点的小数点,进行回溯
dotNum--;
} else {
break; // 只要有一个不合法,直接跳出循环
}
}
}
vector<string> restoreIpAddresses(string s) {
backtracking(s, 0, 0);
return res;
}
};
Python
class Solution:
def __init__(self):
self.dot_num = 0
self.res = []
def isValidIP(self, s, start_index, end_index):
# 每次的start_index都是从目标待添加'.'的位置开始,因此为了防止'.'在最后的情况,需要找个判断
if start_index > end_index:
return False
if start_index != end_index and s[start_index] == '0':
return False
num = 0
if end_index - start_index == 2:
for i in range(start_index, end_index + 1):
if not s[i].isdigit():
return False
num = num * 10 + int(s[i])
if num > 255:
return False
elif end_index - start_index > 2:
return False
return True # 值位于0~255的数
def backtracking(self, s, start_index):
if self.dot_num == 3:
if self.isValidIP(s, start_index, len(s) - 1):
self.res.append(s)
return
for i in range(start_index, len(s)):
if self.isValidIP(s, start_index, i):
self.dot_num += 1
self.backtracking(s[:i + 1] + '.' + s[i + 1:], i + 2)
self.dot_num -= 1
else:
break
def restoreIpAddresses(self, s: str) -> List[str]:
self.backtracking(s, 0)
return self.res
参考文章:93.复原IP地址