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)
相关推荐
Three~stone几秒前
MATLAB vs Python 两者区别和安装教程
开发语言·python·matlab
wsoz9 分钟前
Leetcode子串-day4
c++·算法·leetcode
soragui12 分钟前
【Python】第 1 章:Python 解释器原理
开发语言·python
Ulyanov12 分钟前
卡尔曼滤波技术博客系列:第三篇 雷达目标跟踪:运动模型与坐标转换
python·目标跟踪·系统仿真·雷达电子战
会编程的土豆28 分钟前
【数据结构与算法】二叉树大总结
数据结构·算法·leetcode
nimadan1230 分钟前
生成剧本杀软件2025推荐,创新剧情设计工具引领潮流
人工智能·python
极光代码工作室35 分钟前
基于深度学习的智能垃圾分类系统
python·深度学习·神经网络·机器学习·ai
y = xⁿ40 分钟前
【LeetCode Hot100】动态规划:T70:爬楼梯 T118:杨辉三角形 T198:打家劫舍
算法·leetcode·动态规划
MediaTea44 分钟前
Pandas 操作指南(二):数据选取与条件筛选
人工智能·python·机器学习·数据挖掘·pandas
小陈工1 小时前
Python Web开发入门(十二):使用Flask-RESTful构建API——让后端开发更优雅
开发语言·前端·python·安全·oracle·flask·restful