-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerate_IP_Addresses.cpp
More file actions
43 lines (39 loc) · 1.09 KB
/
Copy pathGenerate_IP_Addresses.cpp
File metadata and controls
43 lines (39 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// ! Date :- 03-10-2022
// * https://practice.geeksforgeeks.org/problems/generate-ip-addresses/1
// Backtracking
class Solution
{
int n;
string s;
vector<string> ans;
void util(int i, int prevVal, int noOfDot, string out)
{
if (prevVal > 255 or noOfDot > 3)
return;
if (i == n)
{
if (noOfDot == 3)
ans.push_back(out);
return;
}
if (prevVal == 0 or prevVal > 25) // 0 can't be a prefix and 25 is the max value of a single digit of ip (255)
util(i + 1, s[i] - '0', noOfDot + 1, (out + '.' + s[i]));
else
{
util(i + 1, prevVal * 10 + (s[i] - '0'), noOfDot, (out + s[i])); // if we don't put a dot
util(i + 1, s[i] - '0', noOfDot + 1, (out + '.' + s[i])); // if we put a dot
}
}
public:
vector<string> genIp(string &s)
{
n = s.length();
if (n > 12 or n < 4)
return ans;
this->s = s;
string out;
out = s[0];
util(1, s[0] - '0', 0, out);
return ans;
}
};