题目:
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)
将一组数转化为可能的IP地址。
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
restore(s, 4, "", res);
return res;
}
void restore(string s, int k, string s1, vector<string> &res)
{
if (k == 0 && s.empty())
res.push_back(s1);
else{
for (int i = 1; i < 4; ++i){
if (s.size() >= i&&isValid(s.substr(0, i)))
{
if (k == 1)
restore(s.substr(i), k - 1, s1 + s.substr(0, i), res);
else
restore(s.substr(i), k - 1, s1 + s.substr(0, i) + ".", res);
}
}
}
}
bool isValid(string s)
{
if (s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0'))
return false;
int r = atoi(s.c_str());
return r <= 255 && r >= 0;
}
};