標籤:style blog color io os ar for div sp
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)
NP問題。也是採用遞迴的解法。基本思路就是取出一個合法的數字,作為IP地址的一項,然後遞迴處理剩下的項。可以想象出一顆樹,每個結點有三個可能的分支(因為範圍是0-255,所以可以由一位兩位或者三位組成)。並且這裡樹的層數不會超過四層,因為IP地址由四段組成,到了之後我們就沒必要再遞迴下去,可以結束了。這裡除了上述的結束條件外,另一個就是字串讀完了。
1 public class Solution { 2 public List<String> restoreIpAddresses(String s) { 3 ArrayList<String> res = new ArrayList<String>(); 4 if (s == null || s.length() == 0) return res; 5 helper(res, "", s, 1, 0); 6 return res; 7 } 8 9 public void helper(ArrayList<String> res, String item, String s, int level, int index) {10 if (index >= s.length()) return;11 if (level == 4) {12 String st = s.substring(index);13 if (isValid(st)) {14 String f = String.format("%s.%s", item, st);15 res.add(f);16 }17 return;18 }19 for (int i=1; i<4&&(index+i<=s.length()); i++) {20 String str = s.substring(index, index+i);21 if (isValid(str)) {22 if (item.length() == 0) {23 helper(res, str, s, level+1, index+i);24 }25 else {26 String temp = String.format("%s.%s", item, str);27 helper(res, temp, s, level+1, index+i);28 }29 }30 }31 }32 33 public boolean isValid(String str) {34 if (str == null || str.length()>3) return false;35 if (str.charAt(0) == ‘0‘ && str.length()>1) return false;36 int num = Integer.parseInt(str);37 if (num>=0 && num<=255) {38 return true;39 }40 return false;41 }42 }
Leetcode: Restore IP addresses