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)
相关推荐
humors22136 分钟前
各厂商工具包网址
java·数据库·python·华为·sdk·苹果·工具包
pzx_0011 小时前
【优化器】 随机梯度下降 SGD 详解
人工智能·python·算法
大邳草民1 小时前
Python 中 global 与 nonlocal 的语义与机制
开发语言·笔记·python
小肝一下1 小时前
每日两道力扣,day8
c++·算法·leetcode·哈希算法·hot100
程序员小远1 小时前
软件测试用例总结
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
2501_948114241 小时前
技术解码:Gemini交互式模拟API与高负载网关的选型逻辑
人工智能·python·ai
AC赳赳老秦2 小时前
OpenClaw text-translate技能:多语言批量翻译,解决跨境工作沟通难题
大数据·运维·数据库·人工智能·python·deepseek·openclaw
JaydenAI2 小时前
[Python编程思想与技巧-01]我所理解的Python元模型
python·元宇宙·元类·元模型
清水白石0082 小时前
《Python 架构师的自动化哲学:从基础语法到企业级作业调度系统与 Airflow 止损实战》
数据库·python·自动化
kaico20182 小时前
python操作数据库
开发语言·数据库·python