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)
相关推荐
世辰辰辰36 分钟前
批量修改图片/文本名子
开发语言·python·批量修改文件名
myenjoy_12 小时前
MQTT 与 Sparkplug B——从车间到云端的最后一公里
网络·python
颜酱4 小时前
LangChain 输出解析器:把模型回复变成你要的数据
python·langchain
2401_873479404 小时前
企业安全运营中,如何用IP离线库提前发现失陷主机?三步实现风险画像
网络·数据库·python·tcp/ip·ip
weixin_523185324 小时前
Java基础知识总结(四):引用数据类型与参数传递机制
java·开发语言·python
sheeta19984 小时前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油4 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
码农飞哥5 小时前
我把RAG召回率从60%提到90%,就改了这两件事
python·知识库·向量检索·rag·效果提示
宸津-代码粉碎机5 小时前
Spring AI企业级实战|从RAG优化到Agent多工具调度
java·大数据·人工智能·后端·python·spring
yuhuofei20215 小时前
【Python入门】Python中的字典dict
python