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.
1.我的解法 哈哈哈,开心,我竟然做出来了,,,真的不知所以然的AC了。。。 不过过程也是调整了很多次
就是递归,每次都进行前两个数字的分割,然后计算第三个数是否相等。若第三个数分割后刚好分割完了,说明整个字符串分割完了,就是对的,返回正确;否则不断循环;当某次加和成功,就递归下一次,用begin记录下一次的开始位置。
开始是直接两次循环,没有套递归,导致出现以下案例:
12122436
则开始时会分割成 1+21 =22,但是这样分割不对,不对时需要重头分割;因此需要加递归。
class Solution {
public:
int get_size(int nums){
int count = 0;
while(nums){
nums = nums / 10;
count++;
}
return count;
}
bool isadditive(string num, int begin){
for(int i = begin; i < num.size()-2; i++){
string s1;
for(int j = i+1; j < num.size(); j++){
s1 = num.substr(begin,i+1-begin);
string s2 = num.substr(i+1,j-i);
int i1 = atoi(s1.c_str());
int i2 = atoi(s2.c_str());
int res = i1 + i2;
int pos = get_size(res);
string s3 = num.substr(j+1, pos);
int i3 = atoi(s3.c_str());
if(res == i3){
if(j+pos+1 == num.size()) return true;
bool res = isadditive(num, i+1);
if(res) return true;
break;
}
if(s2 == "0") break;
}
if(s1=="0") return false;
}
return false;
}
bool isAdditiveNumber(string num) {
if(num.size() < 3) return false;
return isadditive(num,0);
}
};