Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

A natural DFS thought. Several pruning tricks can be applied. Please take care of date type(long long).

class Solution {
    bool _check(string a, string b, string c)
    {    
        int lenc = c.length();
        if (!lenc) return true;
        if(lenc > 1 && c[0] == '0') return false;
        
        int lena = a.length();
        int lenb = b.length();        
        if(lenc < max(lena, lenb) || (lena > 1 && a[0] == '0') || (lenb > 1 && b[0] == '0')) return false;
        
        long long va = stoll(a);
        long long vb = stoll(b);
        
        string ssum = to_string(va + vb);
        int lens = ssum.length();
        if (lens > c.length()) return false;
        string pre = c.substr(0, lens);
        if(pre != ssum) return false;
        
        string rest = c.substr(lens);
        if (rest.length() > 0 && rest[0] == '0') return false;
        
        return _check(b, ssum, rest);
    }
public:
    bool isAdditiveNumber(string num) {
        int n = num.length();
        for(int i = 1; i <= n / 2; i ++) // lena
        {
            string a = num.substr(0, i);
            for(int j = 1; j <= n - 2 * i; j ++) // lenb
            {
                string b = num.substr(i, j);
                string c = num.substr(i + j);
                if (_check(a, b, c))
                {
                    return true;
                }
            }
        }
        return false;
    }
};
posted on 2015-11-19 03:08  Tonix  阅读(313)  评论(0编辑  收藏  举报