s0093
All checks were successful
ci/woodpecker/push/test Pipeline was successful

This commit is contained in:
Sainnhe Park 2023-02-02 18:13:48 +08:00
parent 19212e880b
commit 06929474ee
4 changed files with 78 additions and 2 deletions

View File

@ -0,0 +1,14 @@
#ifndef S0093_RESTORE_IP_ADDRESSES_HPP
#define S0093_RESTORE_IP_ADDRESSES_HPP
#include <string>
#include <vector>
using namespace std;
class S0093 {
public:
vector<string> restoreIpAddresses(string s);
};
#endif

View File

@ -28,10 +28,15 @@ void backtrack(NodeState &node, vector<NodeState> &result, int para1, int para2,
return; return;
} }
// 遍历该节点的所有子节点,即遍历下一层
for (...) {
// 剪枝 // 剪枝
// 当现在的节点不可能出现我们想要的结果时,直接跳过。 // 当现在的节点不可能出现我们想要的结果时,直接跳过。
if (/* out of scope */) {
return;
}
// 遍历该节点的所有子节点,即遍历下一层
for (...) {
// 剪枝也可以在 for 循环中完成
if (/* out of scope */) { if (/* out of scope */) {
continue; continue;
} }

View File

@ -3,3 +3,5 @@
## [131. 分割回文串](https://leetcode.cn/problems/palindrome-partitioning/) ## [131. 分割回文串](https://leetcode.cn/problems/palindrome-partitioning/)
![](https://paste.sainnhe.dev/FHTE.jpg) ![](https://paste.sainnhe.dev/FHTE.jpg)
## [93. 复原 IP 地址](https://leetcode.cn/problems/restore-ip-addresses/)

View File

@ -0,0 +1,55 @@
#include "s0093_restore_ip_addresses.hpp"
bool isValidIpAddressSegment(const string &s, int begin, int end) {
if (begin > end) {
return false;
}
if (s[begin] == '0' && begin != end) { // 0开头的数字不合法
return false;
}
int num = 0;
for (int i = begin; i <= end; i++) {
if (s[i] > '9' || s[i] < '0') { // 遇到非数字字符不合法
return false;
}
num = num * 10 + (s[i] - '0');
if (num > 255) { // 如果大于255了不合法
return false;
}
}
return true;
}
void restoreIpAddressesDFS(vector<int> &dots, vector<string> &result, string &s,
int startIndex) {
// 结束条件
if (dots.size() == 4 && startIndex == s.length()) {
string ip = s.substr(0, dots[0] + 1) + "." +
s.substr(dots[0] + 1, dots[1] - dots[0]) + "." +
s.substr(dots[1] + 1, dots[2] - dots[1]) + "." +
s.substr(dots[2] + 1, dots[3] - dots[2]);
result.push_back(ip);
}
// 剪枝
// 如果已经分成了四段,就没必要再分了
if (dots.size() == 4) {
return;
}
// 遍历当前节点的下一层
for (int i = startIndex; i < startIndex + 3; ++i) {
if (isValidIpAddressSegment(s, startIndex, i)) {
dots.push_back(i);
restoreIpAddressesDFS(dots, result, s, i + 1);
dots.pop_back();
}
}
}
vector<string> S0093::restoreIpAddresses(string s) {
vector<string> result{};
vector<int> dots{};
restoreIpAddressesDFS(dots, result, s, 0);
return result;
}