RestoreIPAddresses Algorithm
The RestoreIPAddresses Algorithm is a backtracking algorithm that aims to find all possible valid IPv4 addresses given a string containing only digits. An IPv4 address is a 32-bit numerical value that is represented in a human-readable format as four decimal numbers separated by periods, with each decimal number ranging from 0 to 255. The algorithm is designed to restore the missing period separators in the input string and generate the complete IP addresses that meet the IPv4 address criteria. The problem is typically solved using a depth-first search approach, where the algorithm starts with an empty IP address and recursively adds segments of the input string as potential parts of the final IP address.
To implement the RestoreIPAddresses Algorithm, one starts by defining a helper function that recursively builds the IP address by adding segments from the input string. The helper function takes the current index in the input string, the number of segments added so far, and the partially built IP address. The base case for the recursion is when the algorithm has added four segments and exhausted the input string, in which case the complete IP address is added to the list of results. Otherwise, the algorithm iterates over the possible segment lengths (1 to 3 digits) and checks if the segment is a valid part of an IPv4 address by ensuring the value is between 0 and 255 and has no leading zeros. If the segment is valid, the algorithm continues the search by recursively calling the helper function with the updated index, incremented segment count, and updated IP address. Once the recursion is complete, the algorithm returns the list of all valid restored IP addresses.
class Solution {
public:
vector<string> restoreIpAddresses(string s) {
vector<string> result;
vector<int> sk;
dfs(result, sk, s, 0, 0);
return result;
}
void dfs(vector<string>& result, vector<int>& sk, const string& s, int val, int pos) {
if (sk.size() > 4) {
return;
}
if (pos == s.size()) {
if (sk.size() < 4 || val != 0) {
return;
}
string ip;
ip += to_string(sk[0]);
for (int i = 1; i < 4; i++) {
ip += ".";
ip += to_string(sk[i]);
}
result.push_back(ip);
return;
}
val = val * 10 + s[pos] - '0';
if (val > 255) {
return;
}
if (val != 0) {
dfs(result, sk, s, val, pos + 1);
}
sk.push_back(val);
dfs(result, sk, s, 0, pos + 1);
sk.pop_back();
}
};