|
| 1 | +package backtracking; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +// https://leetcode.com/problems/restore-ip-addresses/ |
| 8 | +public class RestoreIPAddress { |
| 9 | + |
| 10 | + public static void main(String[] args) { |
| 11 | + RestoreIPAddress obj = new RestoreIPAddress(); |
| 12 | + String s = "25525511135"; |
| 13 | + List<String> resultList = obj.restoreIpAddresses(s); |
| 14 | + System.out.println(Arrays.toString(resultList.toArray())); |
| 15 | + } |
| 16 | + |
| 17 | + public List<String> restoreIpAddresses(String s) { |
| 18 | + List<String> resultList = new ArrayList<String>(); |
| 19 | + if (s == null || s.length() < 4) { |
| 20 | + return resultList; |
| 21 | + } |
| 22 | + |
| 23 | + // DFS |
| 24 | + dfs(resultList, s, 0, "", 0); |
| 25 | + |
| 26 | + return resultList; |
| 27 | + } |
| 28 | + |
| 29 | + private void dfs(List<String> resultList, String s, int start, String stored, int count) { |
| 30 | + //exit |
| 31 | + if (start == s.length() && count == 4) { |
| 32 | + resultList.add(stored); |
| 33 | + } |
| 34 | + |
| 35 | + if (start == s.length() || count == 4) { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + for (int i = 1; i < 4; i++) { |
| 40 | + if (start + i > s.length()) { |
| 41 | + break; |
| 42 | + } |
| 43 | + String part = s.substring(start, start + i); |
| 44 | + if ((part.startsWith("0") && part.length() > 1) || (i == 3 && Integer.valueOf(part) > 255)) { |
| 45 | + continue; |
| 46 | + } |
| 47 | + dfs(resultList, s, start + i, stored + part + (count == 3 ? "" : "."), count + 1); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments