Skip to content

Commit

Permalink
adding 3rd solution (#85)
Browse files Browse the repository at this point in the history
  • Loading branch information
ayshachakure authored Oct 1, 2023
1 parent be3023d commit 3bcfc6e
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions LeetCode/Algorithms/Medium/RestoreIPAddresses.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Solution {
public:
vector<string> restoreIpAddresses(const string& s) {
vector<string> ans;
dfs(s, 0, {}, ans);
return ans;
}

private:
void dfs(const string& s, int start, vector<string>&& path,
vector<string>& ans) {
if (path.size() == 4 && start == s.length()) {
ans.push_back(path[0] + "." + path[1] + "." + path[2] + "." + path[3]);
return;
}
if (path.size() == 4 || start == s.length())
return;

for (int length = 1; length <= 3; ++length) {
if (start + length > s.length())
return; // Out of bound
if (length > 1 && s[start] == '0')
return; // Leading '0'
const string& num = s.substr(start, length);
if (stoi(num) > 255)
return;
path.push_back(num);
dfs(s, start + length, move(path), ans);
path.pop_back();
}
}
};

0 comments on commit 3bcfc6e

Please sign in to comment.