// i j分别分隔开三组数字。前两组相加得到第三组。再继续迭代,第二项第三项相加,直到长度相同。判断与原字符串是否相等。时间复杂度O(n^3)
solution 1
class Solution {
public:
bool isAdditiveNumber(string num) {
for (int i = 1; i < num.size(); ++i) {
string s1 = num.substr(0, i);
if (s1.size() > 1 && s1[0] == '0') break;
for (int j = i + 1; j < num.size(); ++j) {
string s2 = num.substr(i, j - i);
long d1 = stol(s1), d2 = stol(s2);
if ((s2.size() > 1 && s2[0] == '0')) break;
long next = d1 + d2;
string nextStr = to_string(next);
string allStr = s1 + s2 + nextStr;
while (allStr.size() < num.size()) {
d1 = d2;
d2 = next;
next = d1 + d2;
nextStr = to_string(next);
allStr += nextStr;
}
if (allStr == num) return true;
}
}
return false;
}
};
solution2
class Solution {
public:
bool isAdditiveNumber(string num) {
for(int i=1; i<=num.size()/2; i++){
for(int j=1; j<=(num.size()-i)/2; j++){
if(check(num.substr(0,i), num.substr(i,j), num.substr(i+j))) return true;
}
}
return false;
}
bool check(string num1, string num2, string num){
if(num1.size()>1 && num1[0]=='0' || num2.size()>1 && num2[0]=='0') return false;
string sum=add(num1, num2);
if(num==sum) return true;
if(num.size()<=sum.size() || sum.compare(num.substr(0,sum.size()))!=0) return false;
else return check(num2, sum, num.substr(sum.size()));
}
string add(string n, string m){
string res;
int i=n.size()-1, j=m.size()-1, carry=0;
while(i>=0 || j>=0){
int sum=carry+(i>=0 ? (n[i--]-'0') : 0) + (j>=0? (m[j--]-'0') : 0);
res.push_back(sum%10+'0');
carry=sum/10;
}
if(carry) res.push_back(carry+'0');
reverse(res.begin(), res.end());
return res;
}
};