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)
相关推荐
风栖柳白杨2 小时前
【语音识别】Qwen3-ASR原理及部署
人工智能·python·语音识别·xcode·audiolm
OnYoung3 小时前
编写一个Python脚本自动下载壁纸
jvm·数据库·python
愚者游世3 小时前
力扣解决二进制&题型常用知识点梳理
c++·程序人生·算法·leetcode·职场和发展·改行学it
圣保罗的大教堂3 小时前
leetcode 3640. 三段式数组 II 困难
leetcode
R-G-B3 小时前
python 验证每次操作图片处理的顺序是否一致,按序号打上标签,图片重命名
开发语言·python·图片重命名·按序号打上标签·验证图片处理的顺序
Geoking.3 小时前
前缀和算法:从一道 LeetCode 题看区间求和优化思想
算法·leetcode·职场和发展
DFT计算杂谈3 小时前
VASP+Wannier90 计算位移电流和二次谐波SHG
java·服务器·前端·python·算法
北京高端信息科技3 小时前
解决ClustalW中替换矩阵的文件格式
python·生物信息学
serve the people3 小时前
python环境搭建 (九) 极简日志工具 loguru
linux·服务器·python
执着2593 小时前
力扣102、二叉树的层序遍历
数据结构·算法·leetcode