Problem
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.
Follow up:
How would you handle overflow for very large input integers?
Solution
class Solution {
string addTwoStr( const string& opt1, const string& opt2 ){
string rst;
int carry = 0;
for( int idx1 = opt1.size() - 1, idx2 = opt2.size() -1; idx1 >= 0 || idx2 >= 0 || carry != 0 ; idx1--, idx2-- ){
int curSum = carry;
if( idx1 < 0 && idx2 < 0 ){
}
else if( idx1 < 0 ){
curSum += ( opt2[idx2] - '0');
}
else if( idx2 < 0 ){
curSum += ( opt1[idx1] - '0');
}
else if(idx1 >= 0 && idx2 >=0 ){
curSum += ( opt1[idx1] - '0' + opt2[idx2] - '0' );
}
carry = curSum/10;
curSum %= 10;
rst.insert(rst.begin(), curSum + '0');
}
return rst;
}
bool helper( int num1Start, int num2Start, int sumStart, const string& num ){
const int N = num.size();
if ( num1Start >= N || num2Start >= N || sumStart >= N ) return false;
string opt1 = num.substr( num1Start, num2Start - num1Start );
string opt2 = num.substr( num2Start, sumStart - num2Start );
if( opt1.size() > 1 && opt1[0] == '0' ) return false;
if( opt2.size() > 1 && opt2[0] == '0' ) return false;
string goldSum = addTwoStr(opt1, opt2); int goldSize = goldSum.size();
if(num.size() - sumStart < goldSize || goldSum != num.substr( sumStart, goldSize)) return false;
if( sumStart + goldSize == num.size() )
{
return true;
}
return helper( num2Start, sumStart, sumStart + goldSize, num );
}
public:
bool isAdditiveNumber(string num) {
const int N = num.size();
for( int num2Start = 1; num2Start < N - 1; num2Start++ ) {
for( int sumStart = num2Start + 1; sumStart < N; sumStart++){
if(helper( 0, num2Start, sumStart, num)){
return true;
}
}
}
return false;
}
};
本文介绍了一种通过回溯算法来判断一个仅包含数字字符的字符串是否为加成数的方法。加成数是指该字符串的数字能形成一个至少包含三个数的加成序列,每个后续数字都是前两个数字之和。文章提供了一个避免大数溢出的解决方案,并包括了一个用于相加大数字字符串的辅助函数。
748

被折叠的 条评论
为什么被折叠?



