306. Additive Number

Additive number is a string whose digits can form additive sequence.

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

For example:
“112358” is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.

1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
“199100199” is also an additive number, the additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Given a string containing only digits ‘0’-‘9’, write a function to determine if it’s an additive number.

解法1: Recursion

思想比较简单,就是不停的尝试两个可能的number,然后看是否可以满足additive number的条件。用recursion就可以解决。
要注意的是,第一个i的循环只需要到(n - 1) / 2就可以了,因为两个数相加最少也会和较长的数长度相等。
假设第二个数字到位置j,那么第三个数字(两个数字之和的长度)就是n - j, n - j要满足的条件也就是j要满足的条件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public boolean isAdditiveNumber(String num) {
if (num == null || num.length() == 0) {
return false;
}
int n = num.length();
for (int i = 1; i <= (n - 1) / 2; i++) {
if (num.charAt(0) == '0' && i > 1) return false;
for (int j = i + 1; n - j >= Math.max(i, j - i); j++) {
if (num.charAt(i) == '0' && j - i > 1) break;
long first = Long.parseLong(num.substring(0, i));
long second = Long.parseLong(num.substring(i, j));
String rest = num.substring(j);
if (helper(rest, first, second)) return true;
}
}
return false;
}
public boolean helper(String num, long first, long second) {
if (num.length() == 0) return true;
Long sum = first + second;
String s = sum.toString();
if (!num.startsWith(s)) return false;
return helper(num.substring(s.length()), second, sum);
}
}