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)
public class Solution { public List<String> restoreIpAddresses(String s) { List<String> res=new LinkedList<String>(); if(s==null || s.length()<=3) return res; dfs(0,0,new String(""),s,res); return res; } public void dfs(int start,int points,String IPstr,String s,List<String> res){ if(start==s.length()&& points==4){ IPstr=IPstr.substring(0,IPstr.length()-1); res.add(IPstr); return; } if(points>=4) return; if(s.length()-start<4-points) return; if(s.length()-start>(4-points)*3) return; if(start+1<=s.length()){ String sub1=s.substring(start,start+1); dfs(start+1,points+1,IPstr+sub1+".",s,res); } if(start+2<=s.length()){ String sub2=s.substring(start,start+2); if(sub2.compareTo("10")>=0 && sub2.compareTo("99")<=0){ dfs(start+2,points+1,IPstr+sub2+".",s,res); } } if(start+3<=s.length()){ String sub3=s.substring(start,start+3); if(sub3.compareTo("100")>=0 && sub3.compareTo("255")<=0){ dfs(start+3,points+1,IPstr+sub3+".",s,res); } } } }
Restore IP Addresses,布布扣,bubuko.com
原文地址:http://blog.csdn.net/dutsoft/article/details/38645339