题目链接:https://leetcode.com/problems/restore-ip-addresses/tabs/description
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)
class Solution {
private:
void dfs(string &s,vector<string>&res,int startidx,string mstr,int depth)
{
if(depth>4)
return;
if(depth==4&&startidx==s.length())
res.push_back(mstr);
else
{
for(int i=1;i<4;i++)
{
if(startidx+i>s.length()) break;
string subs=s.substr(startidx,i);
if((subs[0]=='0'&&i>1)||(stoi(subs)>=256&&i==3))
continue;
dfs(s,res,startidx+i,mstr+subs+(depth==3?"":"."),depth+1);
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
dfs(s,res,0,"",0);
return res;
}
};
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
string ans;
for(int a=1;a<=3;a++)
{
for(int b=1;b<=3;b++)
{
for(int c=1;c<=3;c++)
{
for(int d=1;d<=3;d++)
{
if(a+b+c+d==s.length())
{
int A=stoi(s.substr(0,a));
int B=stoi(s.substr(a,b));
int C=stoi(s.substr(a+b,c));
int D=stoi(s.substr(a+b+c,d));
if(A<=255 && B<=255 && C<=255 && D<=255)
{
ans=to_string(A)+"."+to_string(B)+"."+to_string(C)+"."+to_string(D);
if(ans.length()==s.length()+3)
{
res.push_back(ans);
}
}
}
}
}
}
}
return res;
}
};