Leetcode 93. Restore IP Addresses
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
A valid IP address consists of exactly four integers (each integer in the range 0-255) separated by single periods and without leading zeros (except for the number “0” itself).
Here is a C++ implementation using backtracking to generate all valid IP addresses from the given string:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
void backtrack(string& s, int start, vector<string>& segments, vector<string>& result) {
// Base case: if we have 4 segments and we have consumed all characters from the string
if (segments.size() == 4) {
if (start == s.size()) {
result.push_back(segments[0] + "." + segments[1] + "." + segments[2] + "." + segments[3]);
}
return;
}
// Explore segments starting at 'start'
for (int len = 1; len <= 3; ++len) {
if (start + len > s.size()) break; // Prevent overflow
string segment = s.substr(start, len);
// Check if the segment is valid
if ((segment[0] == '0' && segment.size() > 1) || (len == 3 && stoi(segment) > 255)) continue;
// Choose
segments.push_back(segment);
// Explore further with this segment added
backtrack(s, start + len, segments, result);
// Un-choose (backtrack)
segments.pop_back();
}
}
vector<string> restoreIpAddresses(string s) {
vector<string> result;
vector<string> segments;
backtrack(s, 0, segments, result);
return result;
}
};
int main() {
Solution sol;
string input = "25525511135";
vector<string> result = sol.restoreIpAddresses(input);
for (string ip : result) {
cout << ip << endl;
}
return 0;
}
The time complexity of this approach can be considered O(1) for practical purposes because:
For larger and more generalized inputs, the complexity would largely depend on the depth of recursion and the number of valid segments tried at each step. Nonetheless, due to the constraints of this problem, it remains efficient with a well-bounded number of potential combinations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?