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)
相关推荐
南山安10 分钟前
让 LLM 与外界对话:使用 Function Calling 实现天气查询工具
人工智能·后端·python
未若君雅裁27 分钟前
LeetCode 18 - 四数之和 详解笔记
java·数据结构·笔记·算法·leetcode
用户12039112947261 小时前
打破信息壁垒:手把手教你实现DeepSeek大模型的天气查询功能
python·openai
鱼骨不是鱼翅1 小时前
力扣hot100----1day
python·算法·leetcode·职场和发展
2501_941236211 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
程序猿_极客1 小时前
【2025 最新】 Python 安装教程 以及 Pycharm 安装教程(超详细图文指南,附常见问题解决)
开发语言·python·pycharm·python安装以及配置
小欣加油1 小时前
leetcode 429 N叉树的层序遍历
数据结构·c++·算法·leetcode·职场和发展
b***66611 小时前
Python 爬虫实战案例 - 获取社交平台事件热度并进行影响分析
开发语言·爬虫·python
chushiyunen1 小时前
django使用笔记
笔记·python·django
Kuo-Teng2 小时前
LeetCode 142: Linked List Cycle II
java·算法·leetcode·链表·职场和发展