leetcode -- 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)

[解题思路]

DFS + Backtracking

给定的字符串分成4段,每段都0<= m <= 255

DFS 终止条件:

1. 剩余位数 > 剩余段数*3

2. 剩余位数 < 剩余段数

3. depth == 4

 

给定的字符串每一位都必须出现在最后生成的ip中,一开始没有注意

当输入为:“010010”

未加line38-40 输出:[0.1.0.10, 0.1.1.0, 0.10.0.10, 0.10.1.0, 0.100.1.0, 1.0.0.10, 1.0.1.0, 10.0.1.0]

系统期望输出为:[0.10.0.10, 0.100.1.0]

故当某一位出现在为0时,则break,停止继续计算num,该位就为0

 1 public static ArrayList<String> restoreIpAddresses(String s) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         ArrayList<String> result = new ArrayList<String>();
 5         if (s == null || s.length() == 0) {
 6             return result;
 7         }
 8         int depth = 0, start = 0;
 9         String ip = "";
10         generate(s, start, depth, result, ip);
11 
12         return result;
13     }
14 
15     private static void generate(String s, int start, int depth,
16             ArrayList<String> result, String ip) {
17         // max = 3 check it
18         if ((s.length() - start) > (4 - depth) * 3) {
19             return;
20         }
21         // min = 1 check it
22         if (s.length() - start < 4 - depth) {
23             return;
24         }
25         if (depth == 4) {
26             ip = ip.substring(0, ip.length() - 1);
27             if(!result.contains(ip))
28                 result.add(ip);
29             return;
30         }
31 
32         int num = 0;
33         for (int i = start; i < Math.min(start + 3, s.length()); i++) {
34             num = num * 10 + (s.charAt(i) - '0');
35             if (num <= 255) {
36                 generate(s, i + 1, depth + 1, result, ip + num + ".");
37             }
38             if(num == 0){
39                 break;
40             }
41         }
42     }

 

posted @ 2013-09-04 19:50  feiling  阅读(736)  评论(1编辑  收藏  举报