递归回溯
import java.util.*;
public class Solution {
/**
*
* @param s string字符串
* @return string字符串ArrayList
*/
static final int SEG_COUNT = 4;
ArrayList<String> res = new ArrayList<>();
int[] segments = new int[SEG_COUNT];
public ArrayList<String> restoreIpAddresses (String s) {
// write code here
if(s == null || "".equals(s)){
return res;
}
dfs(s, 0, 0);
return res;
}
public void dfs(String s, int segId, int segStart){
//segId已经为SEG_COUNT了,停止递归
if(segId == SEG_COUNT){
if(segStart == s.length()){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < SEG_COUNT; i++){
sb.append(segments[i]);
if(i != SEG_COUNT - 1){
sb.append(".");
}
}
res.add(sb.toString());
}
return;
}
//再也找不到答案:还没有找到4段ip地址,就已经遍历到了尾部
if(segStart == s.length()){
return;
}
//如果当前值为0,则当前段的ip地址只能为0
if(s.charAt(segStart) == '0'){
segments[segId] = 0;
dfs(s, segId + 1, segStart + 1);
return;
}
//一般情况,枚举每一种可能性
int addr = 0;
for(int segEnd = segStart; segEnd < s.length(); segEnd ++){
addr = addr * 10 + (s.charAt(segEnd) - '0');
//有效情况下只要继续回溯即可
if(addr > 0 && addr <= 0xFF){
segments[segId] = addr;
dfs(s, segId + 1, segEnd + 1);
}
//直接return即可
else{
break;
}
}
}
}