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)
相关推荐
越甲八千几秒前
python 中match...case 和 C switch case区别
c语言·python·xcode
只对py感兴趣的小蒟蒻25 分钟前
L2-052 吉利矩阵
python
豆芽81934 分钟前
深度学习核心算法
人工智能·python·深度学习·神经网络·机器学习·计算机视觉·卷积神经网络
Leo来编程34 分钟前
Python学习第二十三天
python·学习
换个网名有点难37 分钟前
DJANGO 中间件的白名单配置
python·django
川石课堂软件测试39 分钟前
涨薪技术|k8s设计原理
python·功能测试·云原生·容器·kubernetes·单元测试
独行soc1 小时前
2025年渗透测试面试题总结- shopee-安全工程师(题目+回答)
java·网络·python·科技·面试·职场和发展·红蓝攻防
index_all2 小时前
虾皮(Shopee)商品ID获取商品详情请求示例
数据库·python·搜索引擎
啥都鼓捣的小yao2 小时前
实战3. 利用Pytorch预写好ResNet-18预测电视剧《辛普森一家》中的人物——图像分类
人工智能·pytorch·python·深度学习·分类