枚举
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ret;
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)
{
ret.push_back(ans);
}
}
}
return ret;
}
};
dfs枚举
class Solution {
private:
void dfs(string &s,vector<string>&ret,int startidx,string mstr,int depth)
{
if(depth>4)
return;
if(depth==4&&startidx==s.length())
ret.push_back(mstr);
else
{
for(int i=1;i<4;i++)
{
if(startidx+i>s.length()) continue;
string subs=s.substr(startidx,i);
if(subs[0]=='0'&&i>1||stoi(subs)>=256&&i==3)
continue;
dfs(s,ret,startidx+i,mstr+subs+(depth==3?"":"."),depth+1);
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ret;
dfs(s,ret,0,"",0);
return ret;
}
};