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)
该题要返回所有可能结果,就递归解决了。
每次递归尝试添加1位、2位、3位做一段ip,条件是数值小于255
有个小陷阱,就是ip地址的某一段不能以0开头
class Solution {
public:
vector<string> restoreIpAddresses(string str){
vector<string>result;
if(str.empty())
return result;
string tmpIP;
getAllIP(result, str, tmpIP, 0, 0);
return result;
}
void getAllIP(vector<string>& result, string str, string tmpIP, int k, int i)
{
int len = str.length();
if(i>4)
return;
if(k == len)
{
if(i==4)
{
tmpIP.pop_back();//去掉最后一个'.'
result.push_back(tmpIP);
}
return;
}
string tmp;
tmp += str[k];
if(getvalue(tmp)<=255)
{
tmpIP += (tmp+'.');
getAllIP(result, str, tmpIP,k+1 ,i+1);
tmpIP.pop_back();
tmpIP.pop_back();
}
if(str[k] != '0')
{
if(k < len-1)
{
tmp += str[k+1];
if(getvalue(tmp)<=255)
{
tmpIP += (tmp+'.');
getAllIP(result, str, tmpIP, k+2, i+1);
tmpIP.pop_back();
tmpIP.pop_back();
tmpIP.pop_back();
}
}
if(k < len-2)
{
tmp += str[k+2];
if(getvalue(tmp)<=255)
{
tmpIP += (tmp+'.');
getAllIP(result, str, tmpIP, k+3 ,i+1);
tmpIP.pop_back();
tmpIP.pop_back();
tmpIP.pop_back();
tmpIP.pop_back();
}
}
}
}
int getvalue(string s)
{
int len = s.length();
int result = 0;
for(int i=0; i<len; ++i)
result = 10*result + s[i]-'0';
return result;
}
};