Leetcode 306. Additive Number

Problem

An additive number is a string whose digits can form an additive sequence.

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

Given a string containing only digits, return true if it is an additive number or false otherwise.

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Algorithm

Use DFS to solve the problem, keeping track of the previous two numbers on the path, and continue searching forward if the condition is met.

Code

python3 复制代码
class Solution:
    def isAdditiveNumber(self, num: str) -> bool:
        nlen = len(num)
        def dfs(s, num1, num2, cnts):
            if s == nlen:
                return cnts >= 3

            for i in range(s, nlen):
                if s < i and num[s] == '0':
                    break
                num3 = int(num[s:i+1])
                if cnts >= 2 and num3 != num1 + num2: 
                    continue
                if dfs(i+1, num2, num3, cnts+1):
                    return True
            
            return False

        return dfs(0, 0, 0, 0)
相关推荐
FreakStudio7 分钟前
无硬件学LVGL:基于Web模拟器+MiroPython速通GUI开发—布局与空间管理篇
python·单片机·嵌入式·面向对象·并行计算·电子diy
qq_372906931 小时前
如何在 Vuetify 中可靠捕获 Chip 关闭事件(包括键盘触发)
jvm·数据库·python
Ulyanov1 小时前
用Pyglet打造AI数字猎人:从零开始的Python游戏开发与强化学习实践
开发语言·人工智能·python
zopple1 小时前
ThinkPHP5常见问题及解决方案
python·php·laravel
23471021272 小时前
4.15 学习笔记
开发语言·软件测试·python
qq_372154232 小时前
SQL嵌套查询中常见报错排查_语法与权限处理
jvm·数据库·python
2401_887724503 小时前
CSS如何设置文字溢出显示省略号_利用text-overflowellipsis
jvm·数据库·python
m0_747854523 小时前
golang如何实现应用启动耗时分析_golang应用启动耗时分析实现思路
jvm·数据库·python
解救女汉子3 小时前
如何截断SQL小数位数_使用TRUNCATE函数控制精度
jvm·数据库·python
2301_803875614 小时前
如何用 objectStore.get 根据主键 ID 获取数据库单条数据
jvm·数据库·python