<p>An <strong>additive number</strong> is a string whose digits can form an <strong>additive sequence</strong>.</p>

<p>A valid <strong>additive sequence</strong> should contain <strong>at least</strong> three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.</p>

<p>Given a string containing only digits, return <code>true</code> if it is an <strong>additive number</strong> or <code>false</code> otherwise.</p>

<p><strong>Note:</strong> Numbers in the additive sequence <strong>cannot</strong> have leading zeros, so sequence <code>1, 2, 03</code> or <code>1, 02, 3</code> is invalid.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> &quot;112358&quot;
<strong>Output:</strong> true
<strong>Explanation:</strong> 
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
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> &quot;199100199&quot;
<strong>Output:</strong> true
<strong>Explanation:</strong> 
The additive sequence is: 1, 99, 100, 199.&nbsp;
1 + 99 = 100, 99 + 100 = 199
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= num.length &lt;= 35</code></li>
	<li><code>num</code> consists only of digits.</li>
</ul>

<p>&nbsp;</p>
<p><strong>Follow up:</strong> How would you handle overflow for very large input integers?</p>

class Solution {
public:
    bool func(string num1, string num2, string rem){
        if(rem.length() < max(num1.length(), num2.length()))
            return false;
        if(num1[0] == '0' && num1.length() > 1)
            return false;
        if(num2[0] == '0' && num2.length() > 1)
            return false;
        long long a = stol(num1), b = stol(num2);
        long long res = a + b;
        string ans = to_string(res);
        if(ans == rem) return true;
        if(ans.length() > rem.length()) return false;
        int n = ans.length();
        if(ans == rem.substr(0, n)){
            if(n == rem.length()){
                return true;
            }
            a = b;
            b = res;
            rem = rem.substr(n, rem.length() - n);
            return func(to_string(a), to_string(b), rem);
        }
        return false;
    }

    bool isAdditiveNumber(string num) {
        int n = num.length();
        if(n <= 2) return false;
        for(int i = 0; i < n; i++){
            for(int j = i + 1; j < n; j++){
                string num1 = num.substr(0, i + 1);
                string num2 = num.substr(i + 1, j - i);
                string rem = num.substr(j + 1, n - j);
                //cout << num1 << " "<< num2 <<" "<< rem << endl;
                if(func(num1, num2, rem))
                    return true;
            }
        }
        return false;
    }
};
9600