C++ backtrace simple code


  • 0
    E

    class Solution {
    public:
    bool isAdditiveNumber(string num) {
    return isAdditiveNumber(num, "", "");
    }

    bool isAdditiveNumber(string num, string a, string b)
    {
        for(int i = 1; i <= num.length(); ++i)
        {
            string sum = num.substr(0, i);
            
            if(sum.length() > 1 && sum[0] == '0') continue;
            
            if( a.length() > 0 && b.length() > 0 )
            {
                if(atoi(sum.c_str()) == atoi(a.c_str()) + atoi(b.c_str()))
                {
                    if( i == num.length() ) return true;
                    
                    if( isAdditiveNumber(num.substr(i), b, sum )) return true;
                }
            }
            else if(0 == a.length())
            {
                if( isAdditiveNumber(num.substr(i), sum, "") ) return true;
            }
            else
            {
                if( isAdditiveNumber(num.substr(i), a, sum )) return true;
            }
        }
        
        return false;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.