题目链接:https://leetcode.cn/problems/restore-ip-addresses/
方法一 回溯
1 方法思想
2 代码实现
class Solution {
public List<String> restoreIpAddresses(String s) {
backTracing(s, 0, "", 0);
return result;
}
List<String> result = new ArrayList<>();
public void backTracing(String str, int start, String temp, int nums) {
if (nums == 4 ){
if (start == str.length()) {
result.add(temp);
}
return;
}
for (int i = start; i < str.length(); i++) {
if (i - start > 2) {
return;
}
if (i - start == 2 && Integer.valueOf(str.substring(start, i + 1)) >255) {
return;
}
if (i != start && Integer.valueOf(str.charAt(start) - '0') == 0) {
return;
}
StringBuffer stringBuffer = new StringBuffer(temp);
if (start != 0){
stringBuffer.append(".");
}
stringBuffer.append(str.substring(start, i + 1));
backTracing(str, i + 1, new String(stringBuffer), nums + 1);
stringBuffer.deleteCharAt(stringBuffer.length() - 1);
if (start != 0){
stringBuffer.deleteCharAt(stringBuffer.length() - 1);
}
}
}
}
3 复杂度分析
时间复杂度:
空间复杂度: