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)
相关推荐
2301_812539674 分钟前
CSS如何引入CSS形状生成器_通过自定义属性实现图形化样式
jvm·数据库·python
m0_6091604941 分钟前
Golang怎么实现数据库连接重试_Golang如何在启动时重试连接直到数据库就绪【技巧】
jvm·数据库·python
花米徐1 小时前
技术洞察精选 | 2026年4月28日 — 5月4日
后端·python·flask
宝贝儿好1 小时前
【LLM】第三章:项目实操案例:智能输入法项目
人工智能·python·深度学习·算法·机器人
m0_624578592 小时前
如何在phpMyAdmin中导入GZIP压缩格式文件_加速传输并突破文件大小限制
jvm·数据库·python
m0_495496412 小时前
mysql数据库表名区分大小写吗_通过lower case table names配置
jvm·数据库·python
weixin_459753942 小时前
MySQL主从同步跳过错误影响一致性_使用pt-table-sync修复
jvm·数据库·python
kexnjdcncnxjs2 小时前
如何解决Oracle 12c以上版本的ORA-65096_C##公共用户前缀限制
jvm·数据库·python
zhoutongsheng2 小时前
MySQL触发器无法触发的原因分析_MySQL触发器排查指南
jvm·数据库·python