LeetCode 93. Restore IP Addresses

原题链接在这里:https://leetcode.com/problems/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)

题解:

IP规则, 一共有四段. 每段数字在[0,255], 但当一段起始是0时, 它唯一的合法规则就是单独一个0. 

DFS state: s, current start index, count item, count of segments in the item and res.

一共四段, dfs时用count计数现在是第几段. 到了第四段并且正好走到了s的末位, 把当前item加到res中.

Otherwise, for i in [1,3], get s.substring(start, start+i), of course start + i is within index range. Check if value of substring is legal. 

If yes, then continue DFS. 

Time Complexity: exponential.

Space: O(1). 最多4层stack.

AC Java:

 1 class Solution {
 2     public List<String> restoreIpAddresses(String s) {
 3         List<String> res = new ArrayList<>();
 4         if(s == null || s.length() == 0){
 5             return res;
 6         }
 7         
 8         dfs(s, 0, 0, "", res);
 9         return res;
10     }
11     
12     private void dfs(String s, int start, int count, String item, List<String> res){
13         if(count > 4){
14             return;
15         }
16         
17         if(count == 4 && start == s.length()){
18             res.add(item);
19             return;
20         }
21         
22         for(int i = 1; i < 4 && start + i <= s.length(); i++){
23             String sub = s.substring(start, start + i);
24             if(isLegal(sub)){
25                 dfs(s, start + i, count + 1, item + sub + (count == 3 ? "" : "."), res);
26             }
27         }
28     }
29     
30     private boolean isLegal(String s){
31         if(s.charAt(0) == '0'){
32             return s.equals("0");
33         }
34         
35         int val = Integer.valueOf(s);
36         return val > 0 && val < 256;
37     }
38 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4921883.html