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)
相关推荐
X566112 分钟前
CSS如何处理SSR中CSS引入_在服务端渲染时提取关键CSS
jvm·数据库·python
duke8692672141 小时前
PostgreSQL 中高效插入多对多关联数据的三种方案对比与最佳实践
jvm·数据库·python
狮子座明仔1 小时前
AgentSPEX:当 Agent 框架开始把“控制流“从 Python 里抠出来
开发语言·python
m0_463672201 小时前
mysql数据库如何进行逻辑备份与物理备份对比_优缺点分析
jvm·数据库·python
2401_867623981 小时前
SQL如何进行分组后字符串拼接_使用GROUP_CONCAT或STRING_AGG
jvm·数据库·python
kexnjdcncnxjs1 小时前
MySQL触发器无法触发的原因分析_MySQL触发器排查指南
jvm·数据库·python
Java后端的Ai之路1 小时前
CodeBuddy-Rules配置
人工智能·python·ai编程
拾-光1 小时前
【Git】命令大全:从入门到高手,100 个最常用命令速查(2026 版)
java·大数据·人工智能·git·python·elasticsearch·设计模式
AI玫瑰助手2 小时前
Python流程控制:break与continue语句的区别与应用
开发语言·python·信息可视化
棉猴2 小时前
python海龟绘图之画布与窗口
javascript·python·html·setup·turtle·海龟绘图·screensize