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)
相关推荐
yexuhgu13 分钟前
CSS如何利用-checked实现纯CSS手风琴折叠_通过状态选择器控制区域高度
jvm·数据库·python
AC赳赳老秦19 分钟前
接口测试自动化:用 OpenClaw 对接 Postman,实现批量回归测试、测试报告自动生成与推送
java·人工智能·python·算法·elasticsearch·deepseek·openclaw
PILIPALAPENG23 分钟前
第4周 Day 1:智能体记忆系统——给 Agent 一个"大脑"
前端·人工智能·python
DavidTaozhe28 分钟前
一文搞懂外汇接口怎么实时更新美元汇率
大数据·python
用户78937733908531 小时前
Docker 部署踩坑记录:从“构建失败”到“服务跑通”,以及为什么数据被清空了
python·docker
再玩一会儿看代码1 小时前
如何理解神经网络中的权重参数?从一张图看懂模型参数量计算
人工智能·经验分享·python·深度学习·神经网络·机器学习
2301_779622411 小时前
mysql如何通过主从备份实现读写分离_配置mysql架构模式
jvm·数据库·python
m0_741173331 小时前
HTML5中WebSocket在弱网环境下的延迟抖动算法补偿
jvm·数据库·python
l1t1 小时前
astral-sh发布的musl和gnu版本standalone python 性能比较
开发语言·python
2401_871492851 小时前
Pandas如何做时间差对齐_pd.merge_asof按最近的时间戳合并两表
jvm·数据库·python