题意:
现在有一个只包含数字的字符串,将该字符串转化成IP地址的形式,返回所有可能的情况。
例如:
给出的字符串为"25525522135",
返回["255.255.22.135", "255.255.221.35"]. (顺序没有关系)
方法:
递归回溯
思路:提示:做回溯题时,应该将树的图解画出,再写代码。
![]()
按如上图示递归回溯。横向代表循环,纵向代表递归。
注意点:要消除前缀0,每段的IP值范围是[0,255]。
class Solution {
public:
vector<string> res;
vector<string> restoreIpAddresses(string s) {
dfs(s,0,"",0);//递归
return res;
}
void dfs(string s,int st,string v,int cur){//递归
int len=s.size();
if(cur==3){
if(s.substr(st).size()==0)//如果第四段长度为0.则return
return;
if(s.substr(st).size()>1&&s[st]=='0')//如果第四段含有前缀0.则return
return;
int x=0;
for(int i=st;i<len;i++){
x=x*10+s[i]-'0';
}
if(x<=255){//如果第四段的值小于等于255,才加入结果
v+=s.substr(st);
res.push_back(v);
cout << v << endl;
}
return;
}
int x=0;
for(int i=st;i<len;i++){//循环遍历
//消除前缀0
if(i==st&&s[i]=='0'){//如果某段的第一位为0,则直接递归并且之后break
string t="0.";
dfs(s,i+1,v+t,cur+1);
break;
}else{
x=x*10+s[i]-'0';
if(x<=255){//值小于等于255才递归
string t=to_string(x)+".";
dfs(s,i+1,v+t,cur+1);
}
}
}
}
};
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号