LINT_CODE——恢复IP地址
思路:偷懒的思路是,生成一个0到255的关键字容器,在回溯的时候检测是否合格,合格就继续深层回溯;
class Solution {
public:
/*
* @param s: the IP string
* @return: All possible valid IP addresses
*/
vector<string> restoreIpAddresses(string &s) {
// write your code here
vector<string> res;
//建立一个字典,方便查询时候合格
set<string> dict;
for(int i = 0 ; i <=255 ; i++)
dict.insert(to_string(i));
build(res,s,"",0,0,dict);
return res;
}
void build(vector<string> &res,string &s,string temp,int index,int count,set<string> &dict)
{
if(count > 4)
return;
if(index >= s.size() && count == 4)
{
temp.pop_back();
res.push_back(temp);
return;
}
for(int i = 0 ; i < 3; i++)
{
if(index+i < s.size())
{
string st = s.substr(index,i+1);
if(dict.find(st)!=dict.end())
{
temp += s[index+i];
build(res,s,temp+".",index+i+1,count+1,dict);
}
}
}
}
};