python:
class Solution:
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
def dfs(s, index, path, res):
if index == 4:
if not s:
res.append(path[:-1])
return
for i in range(1,4):
if i <= len(s):
if i == 1:
dfs(s[i:], index+1, path+s[:i]+'.', res)
elif i == 2 and s[0] != '0':
dfs(s[i:], index+1, path+s[:i]+'.', res)
elif i == 3 and s[0] != '0' and int(s[:3]) <= 255:
dfs(s[i:], index+1, path+s[:i]+'.', res)
res = []
dfs(s, 0, '', res)
return res
c++:
class Solution {
void dfs(string s, int index, string space, vector<string> & res){
if(index == 4){
if (s.empty())
res.push_back(space.substr(0, space.size() - 1));
return;
}
for (int i = 1; i < 4; i++){
if (i <= s.size()){
if (i >= 2 && s[0] == '0') continue;
string part = s.substr(0, i);
if (i == 3 && atoi(part.c_str()) > 255) continue;
dfs (s.substr(i), index+1, space+part+".", res);
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
vector<string> res;
dfs (s, 0, "", res);
return res;
}
};