您的位置:首页 > 其它

306. Additive Number

2016-03-23 14:27 399 查看

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 

典型的backtracking .....

这里直接写了个 addTwoStr ( ) 的方法,避免大数溢出。 如果不考虑大数,就可以把两个字符串变成数字,直接用加号。。。

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  back tracking