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)
相关推荐
努力学习_小白5 分钟前
数据增强——tensorflow
人工智能·python·tensorflow
m0_694845576 分钟前
marimo搭建教程:替代Jupyter的交互式开发工具
服务器·ide·python·docker·jupyter·github
csdn2015_10 分钟前
Set<String> 类型取第一条记录
开发语言·windows·python
csdn2015_10 分钟前
List<String> 转换为Set<String>
windows·python·list
Chen--Xing15 分钟前
Python -- 正则表达式
python·正则表达式·数据分析·数据脱敏·2025年能源网络安全大赛
l1t23 分钟前
对在aarch64 Linux环境编译安装的CinderX补充测试
linux·运维·服务器·python·jit
getapi27 分钟前
Windows 11 安装 uv包括:更新、常用命令、Python 管理、环境切换等,(Astral 的 Python 包/环境工具)完整指南
windows·python·uv
智算菩萨31 分钟前
【Pygame】第1章 Pygame入门与环境搭建
python·ai编程·pygame
Dxy123931021639 分钟前
Python 使用 `raise` 报错抛出异常显示 Unicode 码如何解决
开发语言·python
Q741_14739 分钟前
每日一题 力扣 3418. 机器人可以获得的最大金币数 力扣 215. 数组中的第K个最大元素 动态规划 TopK问题 C++ 题解
c++·算法·leetcode·动态规划·topk