Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given “25525511135”,
return [“255.255.11.135”, “255.255.111.35”]. (Order does not matter)
DFS
public List<String> restoreIpAddresses(String s) {
List<String> r = new ArrayList<String>();
if(s == null || s.length() < 4 || s.length() > 12) return r;
restore(r,s,"",0,0);
return r;
}
private void restore(List<String> r,String s,String t,int begin,int index){
if(index > 4) return;
if(begin == s.length() && index == 4){
r.add(t);
return;
}
for(int i = 1;i < 4;i++){
if(begin+i > s.length()) break;
String cur = s.substring(begin,begin+i);
if((cur.startsWith("0") && cur.length() > 1) || (i == 3 && Integer.parseInt(cur) >= 256)) continue;
restore(r,s,t+cur+(index == 3 ? "":"."),begin+i,index+1);
}
}