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"]
``````

C++ 解法一：

``````class Solution {
public:
vector<string> res;
restore(s, 4, "", res);
return res;
}
void restore(string s, int k, string out, vector<string> &res) {
if (k == 0) {
if (s.empty()) res.push_back(out);
}
else {
for (int i = 1; i <= 3; ++i) {
if (s.size() >= i && isValid(s.substr(0, i))) {
if (k == 1) restore(s.substr(i), k - 1, out + s.substr(0, i), res);
else restore(s.substr(i), k - 1, out + s.substr(0, i) + ".", res);
}
}
}
}
bool isValid(string s) {
if (s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0')) return false;
int res = atoi(s.c_str());
return res <= 255 && res >= 0;
}
};
``````

C++ 解法二：

``````class Solution {
public:
vector<string> res;
helper(s, 0, "", res);
return res;
}
void helper(string s, int n, string out, vector<string>& res) {
if (n == 4) {
if (s.empty()) res.push_back(out);
} else {
for (int k = 1; k < 4; ++k) {
if (s.size() < k) break;
int val = atoi(s.substr(0, k).c_str());
if (val > 255 || k != std::to_string(val).size()) continue;
helper(s.substr(k), n + 1, out + s.substr(0, k) + (n == 3 ? "" : "."), res);
}
}
}
};
``````

Java 解法二：

``````public class Solution {
List<String> res = new ArrayList<String>();
helper(s, 0, "", res);
return res;
}
public void helper(String s, int n, String out, List<String> res) {
if (n == 4) {
return;
}
for (int k = 1; k < 4; ++k) {
if (s.length() < k) break;
int val = Integer.parseInt(s.substring(0, k));
if (val > 255 || k != String.valueOf(val).length()) continue;
helper(s.substring(k), n + 1, out + s.substring(0, k) + (n == 3 ? "" : "."), res);
}
}
}
``````

C++ 解法三：

``````class Solution {
public:
vector<string> res;
for (int a = 1; a < 4; ++a)
for (int b = 1; b < 4; ++b)
for (int c = 1; c < 4; ++c)
for (int d = 1; d < 4; ++d)
if (a + b + c + d == s.size()) {
int A = stoi(s.substr(0, a));
int B = stoi(s.substr(a, b));
int C = stoi(s.substr(a + b, c));
int D = stoi(s.substr(a + b + c, d));
if (A <= 255 && B <= 255 && C <= 255 && D <= 255) {
string t = to_string(A) + "." + to_string(B) + "." + to_string(C) + "." + to_string(D);
if (t.size() == s.size() + 3) res.push_back(t);
}
}
return res;
}
};
``````

Java 解法三：

``````public class Solution {
List<String> res = new ArrayList<String>();
for (int a = 1; a < 4; ++a)
for (int b = 1; b < 4; ++b)
for (int c = 1; c < 4; ++c)
for (int d = 1; d < 4; ++d)
if (a + b + c + d == s.length()) {
int A = Integer.parseInt(s.substring(0, a));
int B = Integer.parseInt(s.substring(a, a + b));
int C = Integer.parseInt(s.substring(a + b, a + b + c));
int D = Integer.parseInt(s.substring(a + b + c));
if (A <= 255 && B <= 255 && C <= 255 && D <= 255) {
String t = String.valueOf(A) + "." + String.valueOf(B) + "." + String.valueOf(C) + "." + String.valueOf(D);
if (t.length() == s.length() + 3) res.add(t);
}
}
return res;
}
}
``````

IP to CIDR