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)
利用回溯法,注意几种情况:
0.0.0.0是合法的
01.1.1.1是不合法的
“10000”只能拆成10.0.0.0
class Solution {
public:
vector<string> restoreIpAddresses(string s) { vector<string> result;
string tmp="";
bt(s,result);
return result; } void bt(string s,vector<string> &result,int start=,string tmp="",int left=)
{
left--;
int n=s.length(); //找到的条件
if(left==&&start==n)
{
//去除最后一个点
tmp.pop_back();
result.push_back(tmp);
return;
} //停止条件
if(left==||(n-start)/left>||(n-start)/left==||start>n)
{
return;
} string tmpStr;
if(n-start>=)
{
tmpStr=tmp;
string str1=s.substr(start,);
tmp+=str1;
bt(s,result,start+,tmp+".",left);
tmp=tmpStr;
} if(n-start>=&&s[start]!='')
{
tmpStr=tmp;
string str2=s.substr(start,);
tmp+=str2;
bt(s,result,start+,tmp+".",left);
tmp=tmpStr;
} if(n-start>=&&s[start]!='')
{
tmpStr=tmp;
string str3=s.substr(start,);
int n = atoi(str3.c_str()); if(n<=)
{
tmp+=str3;
bt(s,result,start+,tmp+".",left);
tmp=tmpStr;
}
} }
};