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)
相关推荐
im_AMBER5 分钟前
Leetcode 67 长度为 K 子数组中的最大和 | 可获得的最大点数
数据结构·笔记·学习·算法·leetcode
serve the people10 分钟前
TensorFlow 基础训练循环(简化版 + 补全代码)
人工智能·python·tensorflow
木里先森11 分钟前
解决报错:/lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.32‘ not found
linux·python
爱打代码的小林13 分钟前
numpy库数组笔记
笔记·python·numpy
Misnice21 分钟前
pip 查看当前包列表
windows·python·pip
qq_3561969529 分钟前
day29异常处理@浙大疏锦行
python
互亿无线明明33 分钟前
如何为全球业务构建可扩展的“群发国际短信接口”?
java·c++·python·golang·eclipse·php·erlang
程序员小远33 分钟前
Selenium自动化测试之弹窗处理
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
胡耀超39 分钟前
AI的记忆革命:从Titans架构到长时运行智能体,谷歌Google,Anthropic,NeurIPS 2025
人工智能·python·ai·架构·智能体·上下文·titans
川石课堂软件测试43 分钟前
使用loadrunner调用mysql API进行性能测试
服务器·数据库·python·selenium·mysql·单元测试·自动化