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)
相关推荐
pursuit_csdn1 小时前
LeetCode 1022. Sum of Root To Leaf Binary Numbers
算法·leetcode·深度优先
nimadan121 小时前
**AI漫剧软件2025推荐,解锁高性价比创意制作新体验**
人工智能·python
踩坑记录3 小时前
leetcode hot100 35. 搜索插入位置 medium 二分查找
leetcode
yunhuibin4 小时前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
易辰君5 小时前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python
秀儿还能再秀5 小时前
正则表达式核心语法 + Python的 re 库中常用方法
python·正则表达式
xcLeigh5 小时前
Python入门:Python3 正则表达式全面学习教程
python·学习·正则表达式·教程·python3
仟濹5 小时前
【算法打卡day10(2026-02-24 周二)复习算法:DFS BFS 并查集】
算法·深度优先·图论·dfs·bfs·广度优先·宽度优先
-海绵东东-5 小时前
哈希表······················
算法·leetcode·散列表
多恩Stone6 小时前
【C++ debug】在 VS Code 中无 Attach 调试 Python 调用的 C++ 扩展
开发语言·c++·python