-
Notifications
You must be signed in to change notification settings - Fork 0
/
116. Restrore the IP address.cpp
60 lines (52 loc) · 1.64 KB
/
116. Restrore the IP address.cpp
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public:
vector<string> res;
vector<string> restoreIpAddresses(string s) {
int count=0,dots=0;
string current="";
backtrack(0,1,count,dots,current,s);
return res;
}
void backtrack(int index,int val,int count,int dots,string¤t,string &s){
if(index==s.length()) {
if(dots==3)
res.push_back(current);
return;
}
if(dots>3)
return;
//we have to put a dot here. if we have include 3 digits
if(count==3) {
current.push_back('.');
if(val<=255)
backtrack(index,0,0,dots+1,current,s);
current.pop_back();
return;
}
//we have to include this char (there are not digits in current section)
if(count==0) {
current.push_back(s[index]);
val=s[index]-'0';
backtrack(index+1,val,count+1,dots,current,s);
current.pop_back();
return;
}
//avoid leading zero.
if(count==1&¤t[current.length()-1]=='0') {
current.push_back('.');
backtrack(index,val,0,dots+1,current,s);
current.pop_back();
return;
}
current.push_back('.');
backtrack(index,0,0,dots+1,current,s);
current.pop_back();
current.push_back(s[index]);
val=(val*10)+s[index]-'0';
if(val<=255)
backtrack(index+1,val,count+1,dots,current,s);
val=val/10;
current.pop_back();
return;
}
};