题目地址:Leecode地址
1.问题思路
切割问题采用回溯思想,一般使用DFS查找。
首先观察一下ipv4地址的特点:
① 总共有4段。
② 每段区间为0~255。
按题意,是想将一段字符串分为4段子串,且每段子串的区间为0~255。
这题是典型的回溯思路,可按DFS进行查找,且当前层从【startIndex, s.length】,下层的遍历区间【startIndex+1, s.length】,且深度最大为4。
2.代码实现
class Solution {
List<String> result = new ArrayList<String>();
StringBuilder path = new StringBuilder();
int count = 4;
public List<String> restoreIpAddresses(String s) {
dfs(s, 0);
return result;
}
/**
* 切割字符串
* 1.只能切割成4个子串
* 2.每个子串不能超过255
*
* @param s
* @param startIndex
*/
public void dfs(String s, int startIndex) {
// 已经达到了4层且字符串已经遍历完
if (startIndex >= s.length() && count<=0) {
String item = path.toString();
result.add(item.substring(0, item.length()-1));
return;
}
if (count <= 0) {
return;
}
// 每层的遍历区间
for (int i = startIndex; i < s.length(); i++) {
String item = s.substring(startIndex, i+1);
// ip每位不能超过255, 且首位必须大于0
if (item.length() > 3 || Integer.parseInt(item) > 255 || (item.length() > 1 && item.startsWith("0"))) {
continue;
}
count--;
path.append(item).append(".");
dfs(s, i+1);
count++; // 回溯
path.delete(path.length() - item.length()-1, path.length());
}
}
}
本文介绍了一种使用回溯(DFS)算法解决LeetCode中关于IPv4地址恢复的问题,通过递归切割字符串,确保每段子串在0-255范围内,最终返回所有可能的合法IP地址组合。
961

被折叠的 条评论
为什么被折叠?



