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.
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
Follow up:
How would you handle overflow for very large input integers?
Approach
1.这道题和842. Split Array into Fibonacci Sequence几乎是一样的,不过这里是没有限制数在32位以内,题目的测试样例应该是在64位以内,它是回溯类题,那么我们就用递归回溯去解决,我们要首先要判断递归式,我们其实不确定每次提取多长的字符串,所以我们的递归式是枚举1~nums.size()-pos范围长度的字符串,pos为当前位置,然后我们还用一个vector装之前提取的字符串(已转化为数字),很明显递归边界就是字符串的终点,即pos==nums.size()的时候,然后我们要判断vector里的数字是否能过组成斐波那契数列,所以我们也将递归返回值设为bool,这样当不能组成斐波那契数列的时候,回溯将某个错误数字剔除。
Code
class Solution {
public:
string long_max;
bool isAdditiveNumber(string num) {
vector<long long> nums;
long_max = to_string(LLONG_MAX);
return DFS(nums, num, 0, num.size());
}
bool isvalid(vector<long long> &nums) {
if (nums.size() < 3)return false;
for (int i = 2; i < nums.size(); i++) {
long long a = nums[i - 2];
long long b = nums[i - 1];
long long c = nums[i];
if (a + b != c)return false;
}
return true;
}
bool DFS(vector<long long> &nums, string &str, int pos, int N) {
if (pos == N) {
return isvalid(nums);
}
for (int i = 1; i <= N - pos; i++) {
if (str[pos] == '0'&&i > 1)break;
string sub = str.substr(pos, i);
if (sub.size() > long_max.size() || sub.size() == long_max.size() && sub.compare(long_max) > 0)break;
nums.push_back(stoll(sub));
if ((nums.size()>2 && !isvalid(nums)) || !DFS(nums, str, pos + i, N)) {
nums.pop_back();
}
else {
return true;
}
}
return false;
}
};