class Solution {
public:
bool res = false;
string num;
bool isAdditiveNumber(string num) {
this->num = num;
if(num.size() <= 2) return false;
for(int i = 1; i <= num.size() - 2; i ++){
for(int j = 1; i + j < num.size(); j ++){
string a = num.substr(0, i);
string b = num.substr(i, j);
if(!res && !(a.size() > 1 && a[0] == '0') && !(b.size() > 1 && b[0] == '0'))
dfs(i + j - 1, a, b);
if(res) return true;
}
}
return false;
}
void dfs(int idx, string& a, string& b){
string c = ccl(a, b);
if(idx + c.size() >= num.size()) return;
if(idx + c.size() == num.size() - 1){
string t = num.substr(idx + 1, c.size());
if(c == t) res = true;
return;
}
string t = num.substr(idx + 1, c.size());
if(c == t) dfs(idx + c.size(), b, t);
}
string ccl(string& a, string& b){
string aa, bb;
if(b.size() < a.size()) aa = b, bb = a;
else aa = a, bb = b;
int i1 = aa.size() - 1, i2 = bb.size() - 1;
int t = 0;
vector<char> v;
while(i1 >= 0 && i2 >= 0){
int s = (aa[i1] - '0') + (bb[i2] - '0') + t;
t = s / 10;
auto r = (s % 10) + '0';
v.push_back(r);
i1 --; i2 --;
}
while(i2 >= 0){
int s = (bb[i2] - '0') + t;
t = s / 10;
auto r = (s % 10) + '0';
v.push_back(r);
i2 --;
}
if(t) v.push_back(t + '0');
string ans;
for(int i = v.size() - 1; i >= 0; i --)
ans += v[i] ;
return ans;
}
};