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)
首先是假设第一个地址只有1位,然后依次往下寻找,如果超过临界条件,那么之前push_back的数据需要pop_back,然后退回假设寻找两位
临界条件包括:两位,三位数据的时候首数组不能为0,同时3位数据的时候不能超过255
class Solution {
public:
vector<string> rt;
vector<string> cand;
string str;
vector<string> restoreIpAddresses(string s) {
rt.clear();
cand.clear();
str = s;
if(str.length() > 12)
{
return rt;
}
dfs(0);
return rt;
}
void dfs(int index)
{
//<终止条件,找到满足序列,将数据添加到对应的rt容器中
if(cand.size() == 4 && index == str.length())
{
addCandToRt();
return;
}
//<如果索引已经大于字符串长度,并且大于四个种子返回,当前搜索路径不成功
if(index >= str.length() || cand.size() >= 4)
{
return;
}
cand.push_back(str.substr(index,1));
dfs(index+1);
cand.pop_back();
if(index >= (str.length()-1) || str.substr(index,1) == ("0") || cand.size() >= 4)
{
return;
}
cand.push_back(str.substr(index,2));
dfs(index+2);
cand.pop_back();
if(index >= (str.length()-2) || str.substr(index,1) == ("0") || cand.size() >= 4)
{
return;
}
string s = str.substr(index,3);
int x = atoi(s.c_str());
if(x <= 255)
{
cand.push_back(str.substr(index,3));
dfs(index+3);
cand.pop_back();
}
}
void addCandToRt() {
string ip = cand[0] + "."
+ cand[1] + "."
+ cand[2] + "."
+ cand[3];
rt.push_back(ip);
}
};
其中用到一些C++的基本知识,在此罗列:
容器Vector
申请:vector< typeName > v1; //默认v1为空,故下面的赋值是错误的v1[0]=5;
vector<typeName>v2(v1); 或v2=v1;
添加数据:push_back
清空容器:clear
删除最顶端数据:pop_back
获取对应索引的数据,类似数组取[index]即可