Approach
Depth-first search
For Additive Number, 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
- 34 lines of Java from the credited upstream file 306.java.
- The implementation keeps its working state in language-native values and containers.
- 2 loop blocks 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 boolean isAdditiveNumber(String num) {3 final int n = num.length();4 5 6 for (int i = 0; i < n / 2; ++i) {7 if (i > 0 && num.charAt(0) == '0')8 return false;9 final long firstNum = Long.parseLong(num.substring(0, i + 1));10 11 12 for (int j = i + 1; Math.max(i, j - i) < n - j; ++j) {13 if (j > i + 1 && num.charAt(i + 1) == '0')14 break;15 final long secondNum = Long.parseLong(num.substring(i + 1, j + 1));16 if (dfs(num, firstNum, secondNum, j + 1))17 return true;18 }19 }20 21 return false;22 }23 24 private boolean dfs(final String num, long firstNum, long secondNum, long s) {25 if (s == num.length())26 return true;27 28 final long thirdNum = firstNum + secondNum;29 final String thirdNumStr = String.valueOf(thirdNum);30 return num.indexOf(thirdNumStr, (int) s) == s &&31 dfs(num, secondNum, thirdNum, s + thirdNumStr.length());32 }33}34