Skip to content

Commit ff70a42

Browse files
committed
3
1 parent 7066a20 commit ff70a42

File tree

1 file changed

+29
-33
lines changed

1 file changed

+29
-33
lines changed
Lines changed: 29 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,40 @@
11
class Solution {
22
public:
33
vector<string> restoreIpAddresses(string s) {
4-
// Start typing your C/C++ solution below
5-
// DO NOT write int main() function
6-
7-
vector<string> addresses;
8-
string ip_address;
9-
restoreIpAddressesHelper(s, 0, 0, ip_address, addresses);
10-
return addresses;
4+
vector<string> result;
5+
vector<int> sk;
6+
dfs(result, sk, s, 0, 0);
7+
return result;
118
}
129

13-
void restoreIpAddressesHelper(string& s, int position,
14-
int blocks, string& ip_address, vector<string>& addresses) {
15-
16-
if (position == s.size() && blocks == 4) {
17-
addresses.push_back(ip_address);
10+
void dfs(vector<string>& result, vector<int>& sk, const string& s, int val, int pos) {
11+
if (sk.size() > 4) {
1812
return;
1913
}
20-
21-
// some pruning skills;
22-
if (blocks >= 4) return;
23-
if ((4-blocks) * 3 < s.size() - position) return;
24-
if ((4-blocks) * 3 == s.size() - position) {
25-
for (int i = 0; i < 4 - blocks; i += 3)
26-
if (s[position + i] > '2') return;
14+
15+
if (pos == s.size()) {
16+
if (sk.size() < 4 || val != 0) {
17+
return;
18+
}
19+
string ip;
20+
ip += to_string(sk[0]);
21+
for (int i = 1; i < 4; i++) {
22+
ip += ".";
23+
ip += to_string(sk[i]);
24+
}
25+
result.push_back(ip);
26+
return;
2727
}
2828

29-
int ip = 0;
30-
int ip_length = ip_address.size();
31-
for (int i = position; i < s.size(); i++) {
32-
ip *= 10;
33-
ip += s[i] - '0';
34-
if (ip > 255) break;
35-
if (blocks != 0 && i == position)
36-
ip_address += '.';
37-
ip_address += s[i];
38-
restoreIpAddressesHelper(s, i + 1, blocks + 1, ip_address, addresses);
39-
if (ip == 0) break;
29+
val = val * 10 + s[pos] - '0';
30+
if (val > 255) {
31+
return;
32+
}
33+
if (val != 0) {
34+
dfs(result, sk, s, val, pos + 1);
4035
}
41-
// pass-by-reference is more effective than pass-by-value
42-
ip_address.erase(ip_length, ip_address.size() - ip_length);
36+
sk.push_back(val);
37+
dfs(result, sk, s, 0, pos + 1);
38+
sk.pop_back();
4339
}
44-
};
40+
};

0 commit comments

Comments
 (0)