-----QUESTION-----
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)
-----SOLUTION-----
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
result.clear();
dfs(s, 0, 0);
return result;
}
void dfs(string s, int startPos, int depth)
{
if (depth ==3)
{
string str = s.substr(startPos,s.length()-startPos);
int restStrLen = str.length();
int n = atoi(str.c_str());
if(n>255) return;
if(restStrLen > 1 && s[startPos]=='0') return;
result.push_back(s);
}
else
{
string str = s.substr(startPos,s.length()-startPos);
int restStrLen = str.length();
if(restStrLen>=4-depth)
{
str = s.substr(0,startPos+1)+"."+s.substr(startPos+1,restStrLen-1);
dfs(str, startPos+2, depth+1);
if(s[startPos] == '0') return;
}
if(restStrLen>=5-depth)
{
str = s.substr(0,startPos+2) +"."+s.substr(startPos+2,restStrLen-2);
dfs(str, startPos+3, depth+1);
}
if(restStrLen>=6-depth)
{
str = s.substr(startPos,3);
int n = atoi(str.c_str());
if(n>255) return;
str = s.substr(0,startPos+3)+"."+s.substr(startPos+3,restStrLen-3);
dfs(str, startPos+4, depth+1);
}
}
}
private:
vector<string> result;
};