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?
Credits:
Special thanks to @jeantimex for adding this problem and creating all test cases.
思路:
最直观的思路就是用一个dfs来遍历所有的可能。时间复杂度较高,但是思路其实较为清晰。 需要定义如下几个函数
1. 一个辅助函数用来判断是否两个字符串之和为第三个字符串
2. dfs辅助函数
代码如下:
class Solution {
public:
bool isAdditiveNumber(string num) {
for (int i = 0; i < num.size()/2; i++) {
string pre = num.substr(0,i+1);
int len = pre.size();
for (int j = i+1; j < num.size()-1; j++) { //notice that loop till num.size()-1
string post = num.substr(i+1,j-i);
if (dfs(num,j+1,pre,post))
return true;
}
}
return false;
}
private:
bool dfs(string num,int idx,string pre,string post) {
if (idx == num.size()) {
return true;
}
for (int i = idx; i < num.size(); i++) {
string cur = num.substr(idx,i-idx+1);
if (isvalid(pre,post,cur) && dfs(num,i+1,post,cur))
return true;
}
return false;
}
bool isvalid(string a,string b,string c) {
if ((a[0] == '0' && a.size() != 1)
|| (b[0] == '0' && b.size() != 1)
|| (c[0] == '0' && c.size() != 1))
return false;
long na = stol(a);
long nb = stol(b);
long nc = stol(c);
return (na + nb == nc);
}
};
几点说明,
1. 需要用long,因为test case里面有 INT_MAX+1的
2. 在判断字符串之和的时候,02这样的字符串不能直接转化为2,是不合法的。
3. dfs的parameter传入有两个pre,post,作为前两个字符串的输入。
4. 主函数中要遍历所有的最初可能性,即遍历所有第一步中的pre和post。这里pre只需遍历到num.size()/2即可,而对于post来说,只能遍历到num.size()-2, 如果遍历到最后一个字符num.size()-1的话,idx上来的位置直接将会是num.size(),这就导致了直接在dfs中返回true