题目:
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)
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
dfs(0, 4, s, 0);
return ans;
}
private:
int pos[4];
vector<string> ans;
//判断ip地址是否符合要求
bool isValid(string s, int beg, int end) {
string ip(s, beg, end - beg + 1);
if (ip.size() == 1)
return "0" <= ip && ip <="9";
else if(ip.size() == 2)
return "10" <= ip && ip <= "99";
else if (ip.size() == 3)
return "100" <= ip && ip <= "255";
return false;
}
//深度搜索
void dfs(int depth, int maxDepth, string &s, int start) {
if (depth == maxDepth) {
if (start == s.size()) {
string addr;
int beg = 0;
for (int i = 0; i < 4; i++) {
string ip(s, beg, pos[i] - beg + 1);
beg = pos[i] + 1;
addr += i == 0 ? ip : "." + ip;
}
ans.push_back(addr);
}
return;
}
for (int i = start; i < s.size(); i++) {
if (isValid(s, start, i)) {
pos[depth] = i;
dfs(depth + 1, maxDepth, s, i + 1);
}
}
}
};