您的位置:首页 > 其它

93. Restore IP Addresses

2015-08-06 19:19 543 查看
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)
分析:按照dfs的方式递归的计算,具体见代码注释。需要注意的一点是,为了加快dfs的回溯速度,应该尽可能对dfs过程进行剪枝。
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<string> res;
string tmpres;
restoreIpAddressesRecur(s, 0, 4, tmpres, res);
return res;
}
//从s的start位置开始计算,ip地址还需要num个域(共4个域)
//tmpres表示当前计算好的部分ip
void restoreIpAddressesRecur(string &s, int start, int num,
string &tmpres, vector<string> &res)
{
int len = s.size();
if(num == 0)
{
if(start == len)//已经计算好了一个ip
{
tmpres.erase(--tmpres.end());//去掉最后的“.”
res.push_back(tmpres);
tmpres.push_back('.');
}
return;
}
//不满足最小或最大长度关系
if(len - start < num || len - start > num*3)return;
int tmplen = tmpres.size();
string tmpstr;
for(int i = 1; i <= 3 && start + i <= len; i++)
{//ip地址的一个域最多包含三个数字
if(validRegion(s, start, start+i-1) == false)continue;
tmpstr = s.substr(start, i) + ".";
tmpres += tmpstr;
restoreIpAddressesRecur(s, start+i, num-1, tmpres, res);
tmpres.erase(tmplen, i+1);
}
}
//判断ip地址的一个域是否合法
bool validRegion(string &s, int istart, int iend)
{
if(iend > istart && s[istart] == '0')return false;
int res = 0;
for(int i = istart; i <= iend; i++)
res = res*10 + (s[i] - '0');
if(res >= 0 && res <= 255)return true;
else return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: