Skip to content

Commit d651dd3

Browse files
committed
"Restore IP Addresses"
1 parent a2f1de5 commit d651dd3

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
195195
| 96 | [Unique Binary Search Trees] | [C](src/96.c) |
196196
| 95 | [Unique Binary Search Trees II] | [C++](src/95.cpp) |
197197
| 94 | [Binary Tree Inorder Traversal] | [C](src/94.c) |
198-
| 93 | [Restore IP Addresses] | |
198+
| 93 | [Restore IP Addresses] | [C++](src/93.cpp) |
199199
| 92 | [Reverse Linked List II] | [C](src/92.c) |
200200
| 91 | [Decode Ways] | [C](src/91.c) |
201201
| 90 | [Subsets II] | |

src/93.cpp

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#include <iostream>
2+
#include <string>
3+
#include <vector>
4+
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
vector<string> restoreIpAddresses(string s) {
10+
vector<string> temp;
11+
vector<string> ans;
12+
13+
dfs(s, temp, ans);
14+
15+
return ans;
16+
}
17+
18+
void dfs(string s, vector<string> &temp, vector<string> &ans) {
19+
if (temp.size() == 4 && s.length() == 0) {
20+
ans.push_back(temp[0] + "." + temp[1] + "." + temp[2] + "." + temp[3]);
21+
return;
22+
}
23+
else if (temp.size() >= 4) {
24+
return;
25+
}
26+
27+
for(int i = 1; i <= 3 && i <= s.length(); i++) {
28+
string t = s.substr(0, i);
29+
if (t.length() > 1 && t[0] == '0') break;
30+
if (stoi(t) > 255) break;
31+
temp.push_back(t);
32+
dfs(s.substr(i, s.length() - i), temp, ans);
33+
temp.pop_back();
34+
}
35+
}
36+
};
37+
38+
int main() {
39+
string str = "010010";
40+
Solution s;
41+
vector<string> ret = s.restoreIpAddresses(str);
42+
43+
for (int i = 0; i < ret.size(); i++) {
44+
cout << ret[i] << endl;
45+
}
46+
return 0;
47+
}

0 commit comments

Comments
 (0)