topic:
Given a string containing only numbers to represent an IP address, return all valid IP addresses that may be obtained from s. You can return the answers in any order.
A valid IP address consists of exactly four integers (each integer is between 0 and 255, and cannot contain leading 0), and the integers are separated by'.'.
For example: "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "[email protected]" are invalid IP addresses.
Example 1:
Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]
source:
Problem-solving ideas: backtracking
Define a variable n, store the value of [start, i], when n meets the IP condition, start recursion + backtracking; if not, exit the loop.
- Recursive termination condition: when the number reaches 4 (start from 0 and reach 4, there is no need to judge the situation greater than 4)
- The result meets the condition: when the number reaches 4, and the character string processing is completed
- Pruning condition: the composition number is greater than 255 (illegal IP number)
- Special treatment: 0 in the IP segment is treated separately
class Solution {
public:
vector<string> result;
vector<string> path;
vector<string> restoreIpAddresses(string s) {
back(s, 0);
return result;
}
void back(const string& s, int start) {
if (path.size() == 4) {
if (start == s.size()) {
result.push_back(path[0]+"."+path[1]+"."+path[2]+"."+path[3]);
}
return;
}
if (s[start] == '0') {
path.push_back("0");
back(s, start + 1);
path.pop_back();
return;
}
int n = 0;
for (int i = start; i < s.size(); i++) {
n = n * 10 + s[i] - '0';
if (n > 255) break;
path.push_back(s.substr(start, i - start + 1));
back(s, i + 1);
path.pop_back();
}
}
};