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 sequence1, 2, 03
or1, 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?
class Solution {
public:
/*algorihtm: DFS
*/
bool dfs(string &num,int n,int start,vector<float>&path){
if(start == n){
return path[path.size()-3]+path[path.size()-2]==path[path.size()-1];
}
for(int l = 1;start+l < n+1;l++){
if(num[start]=='0' && l > 1)break;//skip 0 leading string
string cur = num.substr(start,l);
float target = stof(cur);
int size = path.size();
if(size > 1 && (path[size-2]+path[size-1]) != target)continue;
path.push_back(target);
if(dfs(num,n,start+l,path)){
return true;
}
path.pop_back();
}
return false;
}
bool isAdditiveNumber(string num) {
vector<float>path;
return dfs(num,num.size(),0,path);
}
};
class Solution {
public:
/*algorithm: brute force,iterative
eg.112358
*/
string add(sting s1,string s2){
//implement one own add function for number represented by string
//which can avoid the overflow issue
}
bool isAdditiveNumber(string num) {
for(int i = 1;i < num.size();i++){
for(int j=i;j < num.size();j++){
string s1 = num.substr(0,i);
string s2 = num.substr(i,j);
if((s1.size() > 1 && s1[0]=='0')||(s2.size()>1 && s2[0]=='0'))continue;
string s = add(s1,s2);
string now = s1+s2+s;
while(now.size() < num.size()){
s1 = s2;
s2 = s;
s = add(s1,s2);
now += s;
}
if(now == num)return true;
}
}
return false;
}
};