一、题目
二、代码
class Solution
{
public:
//这题深度是固定的
vector<string> return_vector;
vector<string> path;
bool is_effect(string judge_string)
{
int i;
bool result=1;
int temp_num=0;
if(judge_string[0]=='0'&&judge_string.size()>=2) result=0;
else if(judge_string.size()>=4) result=0;
else
{
temp_num=stoi(judge_string);
if(temp_num<0||temp_num>255) result=0;
}
// if(result==0) std::cout<<"错误的IP地址 "<<std::endl;
// if(result==1) std::cout<<"正确的的IP地址 "<<std::endl;
return result;
}
void back_track(int start_point,string s,int now_depth)
{
int i;
string temp_string;
if(path.size()>=5) return;
if(start_point==s.size()) //有条件的往下回溯 结束必为全部有效 但
{
if(now_depth==4)
{
for(i=0;i<3;i++)
{
temp_string+=path[i];
temp_string+='.';
}
temp_string+=path[3];
return_vector.push_back(temp_string);
}
return;
}
for(i=start_point;i<s.size();i++)
{
temp_string=s.substr(start_point,i-start_point+1);
if(is_effect(temp_string)) //深一层
{
now_depth+=1;
path.push_back(temp_string);
// std::cout<<" now_depth "<<now_depth;
// std::cout<<" path.size() "<<path.size()<<std::endl;
back_track(i+1,s,now_depth);
path.pop_back();
now_depth-=1;
}
else //同一层
{
continue;
}
}
}
vector<string> restoreIpAddresses(string s)
{
return_vector.clear();
path.clear();
//int now_depth=0;
//for(int i=0;i<s.size();i++) std::cout<<" "<<s[i];
//std::cout<<std::endl;
back_track(0,s,0);
//is_effect("0255");
return return_vector;
}
};