My solution in Python


  • 0
    D
    def isAN(snum, a, b):      
            c = a + b
            sc = str(c)
            lc = len(sc)
            if snum[:lc] == sc:
                if lc == len(snum):
                    return True
                else:
                    return isAN(snum[lc:], b, c)
            else:
                return False
            
    class Solution(object):
        def isAdditiveNumber(self, num):
            """
            :type num: str
            :rtype: bool
            """
            snum = str(num)
            N = len(snum)
            if N < 3:
                return False
    
            # n^2 combinations of first 2 numbers
            for i in range(N - 2):
                for j in range(i + 1, N - 1):
                    sa = snum[:i + 1]
                    sb = snum[i + 1:j + 1]
    
                    if sb[0] == '0' and len(sb) > 1:
                        continue
                        
                    if isAN(snum[j + 1:], int(sa), int(sb)):
                        return True
    
            return False

Log in to reply
 

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