Approach
Depth-first search
For Restore IP Addresses, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 30 lines of Java from the credited upstream file 93.java.
- The implementation visibly relies on sequence storage.
- 1 loop block detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public List<String> restoreIpAddresses(final String s) {3 List<String> ans = new ArrayList<>();4 dfs(s, 0, new ArrayList<>(), ans);5 return ans;6 }7 8 private void dfs(final String s, int start, List<String> path, List<String> ans) {9 if (path.size() == 4 && start == s.length()) {10 ans.add(String.join(".", path));11 return;12 }13 if (path.size() == 4 || start == s.length())14 return;15 16 for (int length = 1; length <= 3; ++length) {17 if (start + length > s.length()) 18 return;19 if (length > 1 && s.charAt(start) == '0') 20 return;21 final String num = s.substring(start, start + length);22 if (Integer.parseInt(num) > 255)23 return;24 path.add(num);25 dfs(s, start + length, path, ans);26 path.remove(path.size() - 1);27 }28 }29}30