Skip to content

Commit 7a6ea8d

Browse files
author
EmilyYoung71415
committed
feat: 93.restoreIpAddresses
1 parent a6d8f28 commit 7a6ea8d

File tree

1 file changed

+30
-0
lines changed
  • backtracking/93.restore-ip-addresses

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function restoreIpAddresses(s: string): string[] {
2+
const n = s.length;
3+
const res: string[] = [];
4+
const path: number[] = []; // 255.255.11.23
5+
6+
const dfs = (i: number) => {
7+
if (path.length >= 4) {
8+
if (i === n) {
9+
res.push(path.slice().join('.'));
10+
}
11+
return;
12+
}
13+
14+
for (let j = i; j < n; j++) {
15+
// 转换成 Number
16+
const num = Number(s.slice(i, j + 1)); //[start,i]
17+
if (num > 255) break; // 2555 -> [2] [25] [255]都组合一遍
18+
path.push(num);
19+
dfs(j + 1);
20+
path.pop();
21+
// 为什么是后序判断? 0000-> 0.0.0.0
22+
// 后序表示 从后到前的数据 0.11.22.12
23+
if (s[i] === '0') break; // 不可以前导0
24+
}
25+
};
26+
27+
dfs(0);
28+
29+
return res;
30+
}

0 commit comments

Comments
 (0)