Additive Number LeetCode solution in Java

1
class Solution {
2

3
public boolean isAdditiveNumber(String num) {
4
return backtrack(num, 0, 0, 0, 0);
5
}
6

7
public boolean backtrack(String num, int idx, long sum, long prev, int length) {
8
if (idx == num.length()) {
9
return length >= 3;
10
}
11

12
long currLong = 0;
13

14
for (int i = idx; i < num.length(); i++) {
15
// make sure it won't start with 0
16
if (i > idx && num.charAt(idx) == '0') break;
17
currLong = currLong * 10 + num.charAt(i) - '0';
18

19
if (length >= 2) {
20
if (sum < currLong) {
21
// currLong is greater than sum of previous 2 numbers
22
break;
23
} else if (sum > currLong) {
24
// currLong is smaller than sum of previous 2 numbers
25
continue;
26
}
27
}
28
// currLong == sum of previous 2 numbers
29
if (backtrack(num, i + 1, currLong + prev, currLong, length + 1) == true) {
30
return true;
31
}
32
}
33
return false;
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0