Restore IP Addresses

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)

 1 public class Solution {
 2     public ArrayList<String> restoreIpAddresses(String s) {
 3         ArrayList<String> res = new ArrayList<String>();
 4         if(s==null || s.length()<=0) return res;
 5         String ip = "";
 6         DFS(s,0,0,ip,res);
 7         return res;
 8     }
 9     public void DFS(String s,int start,int depth,String ip,ArrayList<String>res){
10         if(start<depth || start>=(depth+1)*3) return ;
11         if(start!=s.length() && depth==4) return;
12         if(depth==4){
13             res.add(ip.substring(0,ip.length()-1));
14             return ;
15         }
16         
17         int num = 0;
18         for(int i=start;i<Math.min(start+3,s.length());i++){
19             num = 10*num+s.charAt(i)-'0';
20             if(num<=255){
21                 DFS(s,i+1,depth+1,ip+num+".",res);
22             }
23             if(num==0){
24                 break;
25             }
26         }
27     }
28 }
View Code

 sum=sum*10+s.charAt(i)-'0';

if(start<depth || start>=(depth+1)*3) return ;

posted @ 2014-02-10 15:32  krunning  阅读(134)  评论(0编辑  收藏  举报