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)
相关推荐
空空潍9 分钟前
hot100-滑动窗口最大值(day11)
数据结构·c++·算法·leetcode
彼岸花开了吗10 分钟前
构建AI智能体:七十八、参数的艺术:如何在有限算力下实现高质量的AI诗歌创作
人工智能·python·llm
guoketg22 分钟前
Vision Transformer(ViT)的讲解和面试题目讲解
人工智能·python·深度学习·vit
iAkuya25 分钟前
(leetcode)力扣100 35 LRU 缓存(双向链表&哈希)
leetcode·链表·缓存
小oo呆30 分钟前
【学习心得】Python的Pydantic(简介)
前端·javascript·python
岚天start30 分钟前
【日志监控方案】Python脚本获取关键字日志信息并推送钉钉告警
python·钉钉·日志监控
叫我:松哥32 分钟前
基于 Flask 框架开发的在线学习平台,集成人工智能技术,提供分类练习、随机练习、智能推荐等多种学习模式
人工智能·后端·python·学习·信息可视化·flask·推荐算法
rgeshfgreh32 分钟前
Python环境管理:uv极速对决Conda全能
python
幻云201033 分钟前
Python机器学习:从入门到精通
python
热爱专研AI的学妹41 分钟前
2026世界杯观赛工具自制指南:实时比分推送机器人搭建思路
开发语言·人工智能·python·业界资讯