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
- 36 lines of C++ from the credited upstream file 306.cpp.
- 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:3 bool isAdditiveNumber(string num) {4 const int n = num.length();5 6 7 for (int i = 0; i < n / 2; ++i) {8 if (i > 0 && num[0] == '0')9 return false;10 const long firstNum = stol(num.substr(0, i + 1));11 12 13 for (int j = i + 1; max(i, j - i) < n - j; ++j) {14 if (j > i + 1 && num[i + 1] == '0')15 break;16 const long secondNum = stol(num.substr(i + 1, j - i));17 if (dfs(num, firstNum, secondNum, j + 1))18 return true;19 }20 }21 22 return false;23 }24 25 private:26 bool dfs(const string& num, long firstNum, long secondNum, long s) {27 if (s == num.length())28 return true;29 30 const long thirdNum = firstNum + secondNum;31 const string& thirdNumStr = to_string(thirdNum);32 return num.find(thirdNumStr, s) == s &&33 dfs(num, secondNum, thirdNum, s + thirdNumStr.length());34 }35};36