题目描述(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.
题目链接
https://leetcode.com/problems/additive-number/description/
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?
算法分析
前两个数确定之后,后面数字的排列也就确定了,因此只需遍历前两个数字的组合,将生成序列与原始序列比较是否一致即可,由于考虑到大数加法的溢出,直接将字符串相加。
提交代码:
class Solution {
public:
bool isAdditiveNumber(string num) {
for (int i = 1; i < num.size(); ++i) {
for (int j = 1; j < num.size() - i; ++j) {
string c1 = num.substr(0, i);
string c2 = num.substr(i, j);
if ((c1.size() > 1 && c1[0] == '0') ||
(c2.size() > 1 && c2[0] == '0')) continue;
string add = stringAdd(c1, c2);
string now = c1 + c2 + add;
while (now.size() < num.size()) {
c1 = c2;
c2 = add;
add = stringAdd(c1, c2);
now += add;
}
if (now == num) return true;
}
}
return false;
}
private:
string stringAdd(string a, string b) {
int carry = 0;
int len1 = a.size(), len2 = b.size();
if(len1 == 0) return b;
else if(len2 == 0) return a;
int length = max(len1, len2);
string result(length, '0');
char c1, c2;
--len1, --len2, --length;
for(; len1 >= 0 || len2 >= 0; --len1, --len2, --length) {
if (len1 < 0) c1 = '0';
else c1 = a[len1];
if (len2 < 0) c2 = '0';
else c2 = b[len2];
int res = c1 - '0' + c2 - '0' + carry;
carry = res / 10;
res %= 10;
result[length] = '0' + res;
}
if (carry != 0) result = '1' + result;
return result;
}
};