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)
相关推荐
大飞记Python8 分钟前
【2026更新】Python基础学习指南(AI版)——03内置函数
人工智能·python
断眉的派大星13 分钟前
pytorch中链式法则求解梯度
人工智能·pytorch·python
6Hzlia21 分钟前
【Hot 100 刷题计划】 LeetCode 39. 组合总和 | C++ 回溯算法与 startIndex 剪枝
c++·算法·leetcode
疯狂成瘾者25 分钟前
text_splitter常见方法
python·langchain
宵时待雨36 分钟前
优选算法专题1:双指针
数据结构·c++·笔记·算法·leetcode
数据知道41 分钟前
claw-code 源码分析:大型移植的测试哲学——如何用 unittest 门禁守住「诚实未完成」的口碑?
开发语言·python·ai·claude code·claw code
炸炸鱼.1 小时前
Python 网络编程入门(简易版)
网络·python
技术小黑1 小时前
TensorFlow学习系列10 | 数据增强
python·深度学习·tensorflow2
万粉变现经纪人1 小时前
如何解决 import aiohttp ModuleNotFoundError: No module named ‘aiohttp’
python·scrapy·beautifulsoup·aigc·pillow·pip·httpx
AC赳赳老秦1 小时前
OpenClaw image-processing技能实操:批量抠图、图片尺寸调整,适配办公需求
开发语言·前端·人工智能·python·深度学习·机器学习·openclaw