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)
Subscribe to see which companies asked this question
使用 回溯法解决:
主要思想: 一个Ip有四部分,第一部分到第三部分的处理方法一样,每部分的位数逐渐增加,如果出现不合法,就回退,第四部分是第一部分到第三部分取得之后剩余的所有部分,如果合法,就直接加入,否者退出。
注意的条件
1)每一部分的首位不能是 0, 如 10.10.10.01(最后一部分不合法)
2)每一部分转为整数之后小于255
class Solution {
public:
void restore(vector<string>& results, string s, string ret, int part, int index) {
if(part == 3) {
string tmp = s.substr(index, s.size() - index);
if(tmp.size() > 1 && tmp[0] == '0')
return;
if(atoi(tmp.c_str()) <= 255 && tmp.size() <= 3 && tmp.size() > 0)
results.push_back(ret + "." + tmp);
return;
}
for(int i = 1; i <= 3 && index + i <= s.size(); i++) {
string tmp = s.substr(index, i);
if(tmp.size() > 1 && tmp[0] == '0')
return;
if(atoi(tmp.c_str()) <= 255) {
string dot = ret == "" ? "" : ".";
restore(results, s, ret + dot + tmp, part + 1, index + i);
}
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> results;
string ret = "";
restore(results, s, ret, 0, 0);
return results;
}
};