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)
相关推荐
大翻哥哥12 小时前
Python 2025:AI工程化与智能代理开发实战
开发语言·人工智能·python
站大爷IP12 小时前
Python文件处理:从基础操作到实战技巧全解析
python
再努力"亿"点点12 小时前
Sklearn(机器学习)实战:鸢尾花数据集处理技巧
开发语言·python
费弗里13 小时前
无需云服务器!通过Plotly Cloud免费快捷部署Dash应用
python·dash
跟橙姐学代码13 小时前
轻松搞定 Python 模块与包导入:新手也能秒懂的入门指南
前端·python·ipython
荏苒追寻13 小时前
Python 爬虫——爬虫基础
python
wdfk_prog13 小时前
Python脚本深度解析:实现基于YMODEM的单片机固件自动化升级
python·单片机·自动化
黑菜钟13 小时前
代码随想录第七天|● 454.四数相加II ● 383. 赎金信 ● 15. 三数之和 18.四数之和
c++·算法·leetcode
海梨花13 小时前
CSP认证练习题目推荐 (1)
算法·深度优先·csp
萧鼎14 小时前
深入解析 Python 的 pytun 库:虚拟网络接口与隧道技术实战指南
服务器·网络·python