
思路
- DFS+递归
- 需要先生成每个分支组的可选组合。
- 递归的终止条件有三个
- 找到了合法IP
- 没凑齐IP数字就用完了
- 凑齐了IP但是还有剩余数字

class Solution {
LinkedList<String> path = new LinkedList<>();
List<String> res = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
dfs(s, 0);
return res;
}
public void dfs(String s, int start) {
if (path.size() == 4 && start == s.length()) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {
sb.append(path.get(i));
if (i != 3) {
sb.append(".");
}
}
res.add(sb.toString());
return;
}
if (path.size() == 4 && start != s.length()) {
return;
}
if (start == s.length() && path.size() != 4) {
return;
}
List<String> combinations = new ArrayList<>();
if (s.charAt(start) == '0') {
combinations.add("0");
} else {
for (int i = 0; i < 3 && start + i < s.length(); i++) {
String combination = s.substring(start, start + i + 1);
if (Integer.parseInt(combination) <= 255) {
combinations.add(combination);
}
}
}
for (int i = 0; i < combinations.size(); i++) {
path.add(combinations.get(i));
dfs(s, start + combinations.get(i).length());
path.removeLast();
}
}
}