561 lines
18 KiB
Markdown
561 lines
18 KiB
Markdown
<p align="center">
|
||
<a href="https://mp.weixin.qq.com/s/RsdcQ9umo09R6cfnwXZlrQ"><img src="https://img.shields.io/badge/PDF下载-代码随想录-blueviolet" alt=""></a>
|
||
<a href="https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw"><img src="https://img.shields.io/badge/刷题-微信群-green" alt=""></a>
|
||
<a href="https://space.bilibili.com/525438321"><img src="https://img.shields.io/badge/B站-代码随想录-orange" alt=""></a>
|
||
<a href="https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ"><img src="https://img.shields.io/badge/知识星球-代码随想录-blue" alt=""></a>
|
||
</p>
|
||
<p align="center"><strong>欢迎大家<a href="https://mp.weixin.qq.com/s/tqCxrMEU-ajQumL1i8im9A">参与本项目</a>,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们收益!</strong></p>
|
||
|
||
|
||
|
||
## 93.复原IP地址
|
||
|
||
[力扣题目链接](https://leetcode-cn.com/problems/restore-ip-addresses/)
|
||
|
||
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
|
||
|
||
有效的 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。
|
||
|
||
例如:"0.1.2.201" 和 "192.168.1.1" 是 有效的 IP 地址,但是 "0.011.255.245"、"192.168.1.312" 和 "192.168@1.1" 是 无效的 IP 地址。
|
||
|
||
示例 1:
|
||
输入:s = "25525511135"
|
||
输出:["255.255.11.135","255.255.111.35"]
|
||
|
||
示例 2:
|
||
输入:s = "0000"
|
||
输出:["0.0.0.0"]
|
||
|
||
示例 3:
|
||
输入:s = "1111"
|
||
输出:["1.1.1.1"]
|
||
|
||
示例 4:
|
||
输入:s = "010010"
|
||
输出:["0.10.0.10","0.100.1.0"]
|
||
|
||
示例 5:
|
||
输入:s = "101023"
|
||
输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]
|
||
|
||
提示:
|
||
0 <= s.length <= 3000
|
||
s 仅由数字组成
|
||
|
||
|
||
## 思路
|
||
|
||
做这道题目之前,最好先把[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)这个做了。
|
||
|
||
这道题目相信大家刚看的时候,应该会一脸茫然。
|
||
|
||
其实只要意识到这是切割问题,**切割问题就可以使用回溯搜索法把所有可能性搜出来**,和刚做过的[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)就十分类似了。
|
||
|
||
切割问题可以抽象为树型结构,如图:
|
||
|
||

|
||
|
||
|
||
## 回溯三部曲
|
||
|
||
* 递归参数
|
||
|
||
在[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)中我们就提到切割问题类似组合问题。
|
||
|
||
startIndex一定是需要的,因为不能重复分割,记录下一层递归分割的起始位置。
|
||
|
||
本题我们还需要一个变量pointNum,记录添加逗点的数量。
|
||
|
||
所以代码如下:
|
||
|
||
```
|
||
vector<string> result;// 记录结果
|
||
// startIndex: 搜索的起始位置,pointNum:添加逗点的数量
|
||
void backtracking(string& s, int startIndex, int pointNum) {
|
||
```
|
||
|
||
* 递归终止条件
|
||
|
||
终止条件和[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)情况就不同了,本题明确要求只会分成4段,所以不能用切割线切到最后作为终止条件,而是分割的段数作为终止条件。
|
||
|
||
pointNum表示逗点数量,pointNum为3说明字符串分成了4段了。
|
||
|
||
然后验证一下第四段是否合法,如果合法就加入到结果集里
|
||
|
||
代码如下:
|
||
|
||
```
|
||
if (pointNum == 3) { // 逗点数量为3时,分隔结束
|
||
// 判断第四段子字符串是否合法,如果合法就放进result中
|
||
if (isValid(s, startIndex, s.size() - 1)) {
|
||
result.push_back(s);
|
||
}
|
||
return;
|
||
}
|
||
```
|
||
|
||
* 单层搜索的逻辑
|
||
|
||
在[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)中已经讲过在循环遍历中如何截取子串。
|
||
|
||
在`for (int i = startIndex; i < s.size(); i++)`循环中 [startIndex, i]这个区间就是截取的子串,需要判断这个子串是否合法。
|
||
|
||
如果合法就在字符串后面加上符号`.`表示已经分割。
|
||
|
||
如果不合法就结束本层循环,如图中剪掉的分支:
|
||
|
||

|
||
|
||
然后就是递归和回溯的过程:
|
||
|
||
递归调用时,下一层递归的startIndex要从i+2开始(因为需要在字符串中加入了分隔符`.`),同时记录分割符的数量pointNum 要 +1。
|
||
|
||
回溯的时候,就将刚刚加入的分隔符`.` 删掉就可以了,pointNum也要-1。
|
||
|
||
代码如下:
|
||
|
||
```
|
||
for (int i = startIndex; i < s.size(); i++) {
|
||
if (isValid(s, startIndex, i)) { // 判断 [startIndex,i] 这个区间的子串是否合法
|
||
s.insert(s.begin() + i + 1 , '.'); // 在i的后面插入一个逗点
|
||
pointNum++;
|
||
backtracking(s, i + 2, pointNum); // 插入逗点之后下一个子串的起始位置为i+2
|
||
pointNum--; // 回溯
|
||
s.erase(s.begin() + i + 1); // 回溯删掉逗点
|
||
} else break; // 不合法,直接结束本层循环
|
||
}
|
||
```
|
||
|
||
## 判断子串是否合法
|
||
|
||
最后就是在写一个判断段位是否是有效段位了。
|
||
|
||
主要考虑到如下三点:
|
||
|
||
* 段位以0为开头的数字不合法
|
||
* 段位里有非正整数字符不合法
|
||
* 段位如果大于255了不合法
|
||
|
||
代码如下:
|
||
|
||
```
|
||
// 判断字符串s在左闭又闭区间[start, end]所组成的数字是否合法
|
||
bool isValid(const string& s, int start, int end) {
|
||
if (start > end) {
|
||
return false;
|
||
}
|
||
if (s[start] == '0' && start != end) { // 0开头的数字不合法
|
||
return false;
|
||
}
|
||
int num = 0;
|
||
for (int i = start; i <= end; i++) {
|
||
if (s[i] > '9' || s[i] < '0') { // 遇到非数字字符不合法
|
||
return false;
|
||
}
|
||
num = num * 10 + (s[i] - '0');
|
||
if (num > 255) { // 如果大于255了不合法
|
||
return false;
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
```
|
||
|
||
## C++代码
|
||
|
||
|
||
根据[关于回溯算法,你该了解这些!](https://programmercarl.com/回溯算法理论基础.html)给出的回溯算法模板:
|
||
|
||
```
|
||
void backtracking(参数) {
|
||
if (终止条件) {
|
||
存放结果;
|
||
return;
|
||
}
|
||
|
||
for (选择:本层集合中元素(树中节点孩子的数量就是集合的大小)) {
|
||
处理节点;
|
||
backtracking(路径,选择列表); // 递归
|
||
回溯,撤销处理结果
|
||
}
|
||
}
|
||
```
|
||
|
||
可以写出如下回溯算法C++代码:
|
||
|
||
```CPP
|
||
class Solution {
|
||
private:
|
||
vector<string> result;// 记录结果
|
||
// startIndex: 搜索的起始位置,pointNum:添加逗点的数量
|
||
void backtracking(string& s, int startIndex, int pointNum) {
|
||
if (pointNum == 3) { // 逗点数量为3时,分隔结束
|
||
// 判断第四段子字符串是否合法,如果合法就放进result中
|
||
if (isValid(s, startIndex, s.size() - 1)) {
|
||
result.push_back(s);
|
||
}
|
||
return;
|
||
}
|
||
for (int i = startIndex; i < s.size(); i++) {
|
||
if (isValid(s, startIndex, i)) { // 判断 [startIndex,i] 这个区间的子串是否合法
|
||
s.insert(s.begin() + i + 1 , '.'); // 在i的后面插入一个逗点
|
||
pointNum++;
|
||
backtracking(s, i + 2, pointNum); // 插入逗点之后下一个子串的起始位置为i+2
|
||
pointNum--; // 回溯
|
||
s.erase(s.begin() + i + 1); // 回溯删掉逗点
|
||
} else break; // 不合法,直接结束本层循环
|
||
}
|
||
}
|
||
// 判断字符串s在左闭又闭区间[start, end]所组成的数字是否合法
|
||
bool isValid(const string& s, int start, int end) {
|
||
if (start > end) {
|
||
return false;
|
||
}
|
||
if (s[start] == '0' && start != end) { // 0开头的数字不合法
|
||
return false;
|
||
}
|
||
int num = 0;
|
||
for (int i = start; i <= end; i++) {
|
||
if (s[i] > '9' || s[i] < '0') { // 遇到非数字字符不合法
|
||
return false;
|
||
}
|
||
num = num * 10 + (s[i] - '0');
|
||
if (num > 255) { // 如果大于255了不合法
|
||
return false;
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
public:
|
||
vector<string> restoreIpAddresses(string s) {
|
||
result.clear();
|
||
if (s.size() > 12) return result; // 算是剪枝了
|
||
backtracking(s, 0, 0);
|
||
return result;
|
||
}
|
||
};
|
||
|
||
```
|
||
|
||
## 总结
|
||
|
||
在[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)中我列举的分割字符串的难点,本题都覆盖了。
|
||
|
||
而且本题还需要操作字符串添加逗号作为分隔符,并验证区间的合法性。
|
||
|
||
可以说是[131.分割回文串](https://programmercarl.com/0131.分割回文串.html)的加强版。
|
||
|
||
在本文的树形结构图中,我已经把详细的分析思路都画了出来,相信大家看了之后一定会思路清晰不少!
|
||
|
||
|
||
|
||
## 其他语言版本
|
||
|
||
java 版本:
|
||
|
||
```java
|
||
class Solution {
|
||
List<String> result = new ArrayList<>();
|
||
|
||
public List<String> restoreIpAddresses(String s) {
|
||
if (s.length() > 12) return result; // 算是剪枝了
|
||
backTrack(s, 0, 0);
|
||
return result;
|
||
}
|
||
|
||
// startIndex: 搜索的起始位置, pointNum:添加逗点的数量
|
||
private void backTrack(String s, int startIndex, int pointNum) {
|
||
if (pointNum == 3) {// 逗点数量为3时,分隔结束
|
||
// 判断第四段⼦字符串是否合法,如果合法就放进result中
|
||
if (isValid(s,startIndex,s.length()-1)) {
|
||
result.add(s);
|
||
}
|
||
return;
|
||
}
|
||
for (int i = startIndex; i < s.length(); i++) {
|
||
if (isValid(s, startIndex, i)) {
|
||
s = s.substring(0, i + 1) + "." + s.substring(i + 1); //在str的后⾯插⼊⼀个逗点
|
||
pointNum++;
|
||
backTrack(s, i + 2, pointNum);// 插⼊逗点之后下⼀个⼦串的起始位置为i+2
|
||
pointNum--;// 回溯
|
||
s = s.substring(0, i + 1) + s.substring(i + 2);// 回溯删掉逗点
|
||
} else {
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 判断字符串s在左闭⼜闭区间[start, end]所组成的数字是否合法
|
||
private Boolean isValid(String s, int start, int end) {
|
||
if (start > end) {
|
||
return false;
|
||
}
|
||
if (s.charAt(start) == '0' && start != end) { // 0开头的数字不合法
|
||
return false;
|
||
}
|
||
int num = 0;
|
||
for (int i = start; i <= end; i++) {
|
||
if (s.charAt(i) > '9' || s.charAt(i) < '0') { // 遇到⾮数字字符不合法
|
||
return false;
|
||
}
|
||
num = num * 10 + (s.charAt(i) - '0');
|
||
if (num > 255) { // 如果⼤于255了不合法
|
||
return false;
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
}
|
||
```
|
||
|
||
python版本:
|
||
```python
|
||
class Solution:
|
||
def restoreIpAddresses(self, s: str) -> List[str]:
|
||
res = []
|
||
path = [] # 存放分割后的字符
|
||
# 判断数组中的数字是否合法
|
||
def isValid(p):
|
||
if p == '0': return True # 解决"0000"
|
||
if p[0] == '0': return False
|
||
if int(p) > 0 and int(p) <256: return True
|
||
return False
|
||
|
||
def backtrack(s, startIndex):
|
||
if len(s) > 12: return # 字符串长度最大为12
|
||
if len(path) == 4 and startIndex == len(s): # 确保切割完,且切割后的长度为4
|
||
res.append(".".join(path[:])) # 字符拼接
|
||
return
|
||
|
||
for i in range(startIndex, len(s)):
|
||
if len(s) - startIndex > 3*(4 - len(path)): continue # 剪枝,剩下的字符串大于允许的最大长度则跳过
|
||
p = s[startIndex:i+1] # 分割字符
|
||
if isValid(p): # 判断字符是否有效
|
||
path.append(p)
|
||
else: continue
|
||
backtrack(s, i + 1) # 寻找i+1为起始位置的子串
|
||
path.pop()
|
||
backtrack(s, 0)
|
||
return res
|
||
```
|
||
```python
|
||
class Solution(object):
|
||
def restoreIpAddresses(self, s):
|
||
"""
|
||
:type s: str
|
||
:rtype: List[str]
|
||
"""
|
||
ans = []
|
||
path = []
|
||
def backtrack(path, startIndex):
|
||
if len(path) == 4:
|
||
if startIndex == len(s):
|
||
ans.append(".".join(path[:]))
|
||
return
|
||
for i in range(startIndex+1, min(startIndex+4, len(s)+1)): # 剪枝
|
||
string = s[startIndex:i]
|
||
if not 0 <= int(string) <= 255:
|
||
continue
|
||
if not string == "0" and not string.lstrip('0') == string:
|
||
continue
|
||
path.append(string)
|
||
backtrack(path, i)
|
||
path.pop()
|
||
|
||
backtrack([], 0)
|
||
return ans```
|
||
```
|
||
|
||
```python3
|
||
class Solution:
|
||
def __init__(self) -> None:
|
||
self.s = ""
|
||
self.res = []
|
||
|
||
def isVaild(self, s: str) -> bool:
|
||
if len(s) > 1 and s[0] == "0":
|
||
return False
|
||
|
||
if 0 <= int(s) <= 255:
|
||
return True
|
||
|
||
return False
|
||
|
||
def backTrack(self, path: List[str], start: int) -> None:
|
||
if start == len(self.s) and len(path) == 4:
|
||
self.res.append(".".join(path))
|
||
return
|
||
|
||
for end in range(start + 1, len(self.s) + 1):
|
||
# 剪枝
|
||
# 保证切割完,s没有剩余的字符。
|
||
if len(self.s) - end > 3 * (4 - len(path) - 1):
|
||
continue
|
||
if self.isVaild(self.s[start:end]):
|
||
# 在参数处,更新状态,实则创建一个新的变量
|
||
# 不会影响当前的状态,当前的path变量没有改变
|
||
# 因此递归完不用path.pop()
|
||
self.backTrack(path + [self.s[start:end]], end)
|
||
|
||
def restoreIpAddresses(self, s: str) -> List[str]:
|
||
# prune
|
||
if len(s) > 3 * 4:
|
||
return []
|
||
self.s = s
|
||
self.backTrack([], 0)
|
||
return self.res
|
||
```
|
||
|
||
JavaScript:
|
||
|
||
```js
|
||
/**
|
||
* @param {string} s
|
||
* @return {string[]}
|
||
*/
|
||
var restoreIpAddresses = function(s) {
|
||
const res = [], path = [];
|
||
backtracking(0, 0)
|
||
return res;
|
||
function backtracking(i) {
|
||
const len = path.length;
|
||
if(len > 4) return;
|
||
if(len === 4 && i === s.length) {
|
||
res.push(path.join("."));
|
||
return;
|
||
}
|
||
for(let j = i; j < s.length; j++) {
|
||
const str = s.substr(i, j - i + 1);
|
||
if(str.length > 3 || +str > 255) break;
|
||
if(str.length > 1 && str[0] === "0") break;
|
||
path.push(str);
|
||
backtracking(j + 1);
|
||
path.pop()
|
||
}
|
||
}
|
||
};
|
||
```
|
||
Go:
|
||
> 回溯(对于前导 0的IP(特别注意s[startIndex]=='0'的判断,不应该写成s[startIndex]==0,因为s截取出来不是数字))
|
||
|
||
```go
|
||
func restoreIpAddresses(s string) []string {
|
||
var res,path []string
|
||
backTracking(s,path,0,&res)
|
||
return res
|
||
}
|
||
func backTracking(s string,path []string,startIndex int,res *[]string){
|
||
//终止条件
|
||
if startIndex==len(s)&&len(path)==4{
|
||
tmpIpString:=path[0]+"."+path[1]+"."+path[2]+"."+path[3]
|
||
*res=append(*res,tmpIpString)
|
||
}
|
||
for i:=startIndex;i<len(s);i++{
|
||
//处理
|
||
path:=append(path,s[startIndex:i+1])
|
||
if i-startIndex+1<=3&&len(path)<=4&&isNormalIp(s,startIndex,i){
|
||
//递归
|
||
backTracking(s,path,i+1,res)
|
||
}else {//如果首尾超过了3个,或路径多余4个,或前导为0,或大于255,直接回退
|
||
return
|
||
}
|
||
//回溯
|
||
path=path[:len(path)-1]
|
||
}
|
||
}
|
||
func isNormalIp(s string,startIndex,end int)bool{
|
||
checkInt,_:=strconv.Atoi(s[startIndex:end+1])
|
||
if end-startIndex+1>1&&s[startIndex]=='0'{//对于前导 0的IP(特别注意s[startIndex]=='0'的判断,不应该写成s[startIndex]==0,因为s截取出来不是数字)
|
||
return false
|
||
}
|
||
if checkInt>255{
|
||
return false
|
||
}
|
||
return true
|
||
}
|
||
|
||
```
|
||
|
||
C:
|
||
```c
|
||
//记录结果
|
||
char** result;
|
||
int resultTop;
|
||
//记录应该加入'.'的位置
|
||
int segments[3];
|
||
int isValid(char* s, int start, int end) {
|
||
if(start > end)
|
||
return 0;
|
||
if (s[start] == '0' && start != end) { // 0开头的数字不合法
|
||
return false;
|
||
}
|
||
int num = 0;
|
||
for (int i = start; i <= end; i++) {
|
||
if (s[i] > '9' || s[i] < '0') { // 遇到非数字字符不合法
|
||
return false;
|
||
}
|
||
num = num * 10 + (s[i] - '0');
|
||
if (num > 255) { // 如果大于255了不合法
|
||
return false;
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
|
||
//startIndex为起始搜索位置,pointNum为'.'对象
|
||
void backTracking(char* s, int startIndex, int pointNum) {
|
||
//若'.'数量为3,分隔结束
|
||
if(pointNum == 3) {
|
||
//若最后一段字符串符合要求,将当前的字符串放入result种
|
||
if(isValid(s, startIndex, strlen(s) - 1)) {
|
||
char* tempString = (char*)malloc(sizeof(char) * strlen(s) + 4);
|
||
int j;
|
||
//记录添加字符时tempString的下标
|
||
int count = 0;
|
||
//记录添加字符时'.'的使用数量
|
||
int count1 = 0;
|
||
for(j = 0; j < strlen(s); j++) {
|
||
tempString[count++] = s[j];
|
||
//若'.'的使用数量小于3且当前下标等于'.'下标,添加'.'到数组
|
||
if(count1 < 3 && j == segments[count1]) {
|
||
tempString[count++] = '.';
|
||
count1++;
|
||
}
|
||
}
|
||
tempString[count] = 0;
|
||
//扩容result数组
|
||
result = (char**)realloc(result, sizeof(char*) * (resultTop + 1));
|
||
result[resultTop++] = tempString;
|
||
}
|
||
return ;
|
||
}
|
||
|
||
int i;
|
||
for(i = startIndex; i < strlen(s); i++) {
|
||
if(isValid(s, startIndex, i)) {
|
||
//记录应该添加'.'的位置
|
||
segments[pointNum] = i;
|
||
backTracking(s, i + 1, pointNum + 1);
|
||
}
|
||
else {
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
char ** restoreIpAddresses(char * s, int* returnSize){
|
||
result = (char**)malloc(0);
|
||
resultTop = 0;
|
||
backTracking(s, 0, 0);
|
||
*returnSize = resultTop;
|
||
return result;
|
||
}
|
||
```
|
||
|
||
|
||
-----------------------
|
||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码.jpg width=450> </img></div>
|