93. Restore IP Addresses
题目
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)
解析
-
三重循环,遍历三个小数点的位置,对每个位置check一下即可:【LeetCode】93. Restore IP Addresses](https://www.cnblogs.com/ganganloveu/p/3780607.html)
-
递归,ip地址分4组,检查每组的合法性。
class Solution_93 {
public:
bool isValid(string str)
{
long temp = atol(str.c_str()); //用int溢出;atol
if (temp>255)
{
return false;
}
if (str[0]=='0'&&str.size()>1)
{
return false;
}
return true;
}
void dfs(vector<string> &res, string t, string s, int cnt)
{
if (cnt>3)
{
return;
}
if (cnt==3&&isValid(s)) //最后一组数
{
res.push_back(t+s);
return;
}
for (int i = 1; i < 4 && i < s.size();i++)
{
string sub = s.substr(0, i);
if (isValid(sub))
{
dfs(res, t + sub + '.', s.substr(i), cnt + 1);
}
}
return;
}
vector<string> restoreIpAddresses(string s) {
vector<string> res;
string t;
dfs(res,t,s,0);
return res;
}
};