c++
class Solution {
public:
bool isAdditiveNumber(string num) {
if (num.size() < 3) return false;
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;
}
private:
bool check(const string &s1, const string &s2, const string &sum) {
if (s1.size() > 1 && s1[0] == '0') return false;
if (s2.size() > 1 && s2[0] == '0') return false;
string res = addString(s1, s2);
if (res == sum) return true;
if (res.size() > sum.size()) return false;
if (sum.substr(0, res.size()) != res) return false;
return check(s2, res, sum.substr(res.size()));
}
string addString(const string &s1, const string &s2) {
if (s1.empty()) return s2;
if (s2.empty()) return s1;
string res;
int i = s1.size()-1;
int j = s2.size()-1;
int update = 0;
while (i >= 0 || j >= 0) {
int sum = (i >= 0 ? s1[i--] - '0' : 0) + (j >= 0 ? s2[j--] - '0' : 0) + update;
res.push_back(sum % 10 + '0');
update = sum / 10;
}
if (update)
res.push_back(update + '0');
reverse(res.begin(), res.end());
return res;
}
};
reference:
https://leetcode.com/discuss/70124/0ms-concise-solution-perfectly-handles-the-follow-leading