JohnShen's Blog.

[Leetcode单排] 复原IP地址 (N93)

字数统计: 296阅读时长: 1 min
2019/08/04 Share

93. Restore IP Addresses

https://leetcode.com/problems/restore-ip-addresses/

DFS 回溯 典型问题,只要稍微留意一下为 0 的情况就可以了。

需要留意的是终止条件fields == 4 || index == chars.length。之前误写的是fields > 4 || index == chars.length,导致内存 less than 5%。本以为是递归数据结构用的不好,结果发现只要内存用得多,那就应该想到是递归本身条件写的有问题。改回等号后 less than 100%。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<>();
if (s == null || s.length() == 0) {
return result;
}
search(s.toCharArray(), 0,0, "", result);
return result;
}

private void search(char[] chars, int index, int fields, String cur, List<String> result) {
if (fields == 4 && index == chars.length) {
result.add(cur.substring(0, cur.length() - 1));
return;
}
// 注意终止条件
if (fields == 4 || index == chars.length) {
return;
}
if (chars[index] == '0') {
search(chars, index + 1, fields + 1, cur + new String(chars, index, 1) + ".", result);
} else {
if (index + 2 < chars.length && Integer.parseInt(new String(chars, index, 3)) <= 255) {
search(chars, index + 3, fields + 1, cur + new String(chars, index, 3) + ".", result);
}
if (index + 1 < chars.length) {
search(chars, index + 2, fields + 1, cur + new String(chars, index, 2) + ".", result);
}
search(chars, index + 1, fields + 1, cur + new String(chars, index, 1) + ".", result);
}
}
CATALOG
  1. 1. 93. Restore IP Addresses