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)
DFS、回溯
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector< string> res;
if( s.size() < 4 || s.size() > 12)
return res;
core( res, s, 0, "");
return res;
}
void core( vector< string> &res, string s, int index, string cur){
if( s.size() == index && cur.size() == s.size() + 4){
cur.pop_back();
res.push_back(cur);
return;
}
if( index > s.size() || cur.size() > s.size() + 4)
return;
if( s[index] == '0')//这里要考虑如果首位是0,那么这各的ip就是0了,可以直接往下继续搜,不用考虑两位数和三位数的情况
core( res, s, index + 1, cur + "0.");
else{
for( int j = 1; j <= 3; ++j){
string tmp = s.substr( index, j);
int valid = atoi( tmp.c_str());
if( valid < 256 && valid >= 0){
core( res, s, index + j, cur+tmp+'.');
}
}
}
}
};