Compact Python solution

  • 1
    class Solution(object):
        def isAdditiveNumber(self, num, i=0, n=1, pre2=None, pre1=None):
            if i == len(num): return n > 3
            for size in range(1, len(num)-i+1):
                if size > 1 and num[i] == '0': return False
                v = int(num[i: i+size])
                if n > 2 and not v == pre2 + pre1: continue
                if self.isAdditiveNumber(num, i+size, n+1, pre1, v): return True
            return False

  • 0

    It's a good solution,but I can't understand what does n mean,can you explain your algorithm to us briefly,thanks very much!

  • 1

    n means the nth number to process, only numbers after 2nd number should be checked by the additive number rule:

    1st + 2nd = 3rd
    2nd + 3rd = 4th
    3rd + 4th = 5th

    which is implemented as:

    if n > 2 and not v == pre2 + pre1: continue

Log in to reply

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