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)
相关推荐
n***27194 分钟前
JAVA (Springboot) i18n国际化语言配置
java·spring boot·python
心无旁骛~6 分钟前
python多进程multiprocessing——spawn启动方式解析
开发语言·python
家家小迷弟15 分钟前
docker容器内部安装python和numpy的方法
python·docker·numpy
conkl18 分钟前
Python中的鸭子类型:理解动态类型的力量
开发语言·python·动态·鸭子类型·动态类型规划
.柒宇.20 分钟前
力扣hot100---42.接雨水(java版)
java·算法·leetcode
故事挺秃然22 分钟前
Python异步(Asyncio)(一)
服务器·网络·python
大飞记Python28 分钟前
【2025全攻略】PyCharm专业版 / 社区版如何打开.db 数据库文件
数据库·python·sql·pycharm
坚持就完事了39 分钟前
数据结构之链表
数据结构·python·算法·链表
木头左1 小时前
自动化超参搜索框架在PCA参数调优中的应用
python
apihz1 小时前
域名注册状态查询免费API接口详细教程
android·服务器·网络·python·tcp/ip