306. Additive Number
Medium
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.
Given a string containing only digits ‘0’-‘9’, write a function to determine if it’s an additive number.
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.
Example 1:
Input: “112358”
Output: true
Explanation: 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
Example 2:
Input: “199100199”
Output: true
Explanation: The additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
题意
给定一个数字组成的字符串,判断是否可以分割成数字序列,使得序列中每个数字都是由前两个数字相加而成(第一个和第二个数字除外)。含有先导零的数字不合法(例如03是非法数字)。
思路
搜索 + 简单的剪枝(第一个数字和第二个数字的长度不可能超过字符串剩余长度的一半)。
代码
class Solution {
/**
@param str Input string
@param begin Begin index of this recursion
@param expected Expected value of this recursion
@param prev Previous value
@return If is additive number
*/
private boolean recursive(String str, int begin, long expected, long prev) {
if (begin == str.length()) {
return true;
}
int n = str.length() - begin, i = begin, bound = n;
if (prev == -1 && expected == -1) { // first recusion
bound = n/2;
for (i=begin+1; i<=begin+bound; ++i) {
if (i > begin+1 && str.charAt(begin) == '0') {
continue;
}
if (recursive(str, i, -1, Long.parseLong(str.substring(begin, i)))) {
return true;
}
}
} else if (expected == -1) { // second recusion
bound = n/2;
for (i=begin+1; i<=begin+bound; ++i) {
if (i > begin+1 && str.charAt(begin) == '0') {
continue;
}
long tmp = Long.parseLong(str.substring(begin, i));
if (recursive(str, i, tmp+prev, tmp)) {
return true;
}
}
} else {
bound = n;
for (i=begin+1; i<=begin+bound; ++i) {
if (i > begin+1 && str.charAt(begin) == '0') {
continue;
}
long tmp = Long.parseLong(str.substring(begin, i));
if (tmp == expected && recursive(str, i, tmp+prev, tmp)) {
return true;
}
}
}
return false;
}
public boolean isAdditiveNumber(String num) {
return recursive(num, 0, -1, -1);
}
}