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)
相关推荐
snow_star_dream19 分钟前
(笔记)VSC python应用--函数补全注释添加
笔记·python
郝学胜-神的一滴30 分钟前
Python中的Mixin继承:灵活组合功能的强大模式
开发语言·python·程序人生
June bug30 分钟前
(#数组/链表操作)最长上升子序列的长度
数据结构·程序人生·leetcode·链表·面试·职场和发展·跳槽
叫我:松哥31 分钟前
基于python强化学习的自主迷宫求解,集成迷宫生成、智能体训练、模型评估等
开发语言·人工智能·python·机器学习·pygame
hadage23333 分钟前
--- 力扣oj柱状图中最大的矩形 单调栈 ---
算法·leetcode·职场和发展
json{shen:"jing"}33 分钟前
18. 四数之和
数据结构·算法·leetcode
2301_7644413335 分钟前
2025年YOLO算法案例应用领域应用趋势
python·yolo
汗流浃背了吧,老弟!44 分钟前
构建RAG系统时,如何选择合适的嵌入模型(Embedding Model)?
人工智能·python·embedding
盐真卿1 小时前
python第四部分:模块(每日更新)
开发语言·python
多米Domi0111 小时前
0x3f 第42天 复习 10:39-11:33
算法·leetcode