解决思路
回溯
class Solution {
private List<String> res;
private int n;
String str;
public List<String> restoreIpAddresses(String s) {
res = new ArrayList<>();
n = s.length();
str = s;
backtrack(0, "", 4);
return res;
}
//flag为分为4段
private void backtrack(int i,String temp,int flag){
if (i == n && flag == 0){
//去掉最后的.
res.add(temp.substring(0,temp.length()-1));
return;
}
if (flag < 0) return;
for (int j = i;j < i + 3 && j < n;j++){
//对0特别判断
if (i == j && str.charAt(j) == '0'){
backtrack(j + 1,temp + str.charAt(j) + ".",flag - 1);
break;
}
//判断是否小于255
if (Integer.parseInt(str.substring(i,j+1)) <= 255){
backtrack(j + 1,temp + str.substring(i, j + 1) + ".",flag - 1);
}
}
}
}