您的位置:首页 > 其它

93. Restore IP Addresses

2016-05-25 10:19 197 查看
枚举

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: