题目描述:
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
Example:
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]
程序:
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> v;
dfs(s, 0, "", v);
return v;
}
private:
void dfs(string s, int point, string ip, vector<string>& v) {
int l = s.size();
if (point == 4) {
if (l == 0) {
ip = ip.substr(0, ip.size()-1);
v.push_back(ip);
}
return;
}
for (int i = 1; i <= min(3, s[0] == '0' ? 1:l); i++) {
string ss = s.substr(0, i);
if (stoi(ss) > 255) return;
dfs(s.substr(i,s.size()-i), point+1, ip + ss + '.', v);
}
}
};