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)
相关推荐
vvoennvv16 分钟前
【Python TensorFlow】 CNN-GRU卷积神经网络-门控循环神经网络时序预测算法(附代码)
python·神经网络·机器学习·cnn·gru·tensorflow
吗~喽18 分钟前
【LeetCode】滑动窗口_水果成篮_C++
c++·算法·leetcode
程序员三藏1 小时前
软件测试之压力测试详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·压力测试
BINGCHN1 小时前
流量分析进阶(一):RCTF2025-Shadows of Asgard
开发语言·python
GeekPMAlex1 小时前
Python SQLite多线程、上下文管理器与生成器全面解析
python
顾安r1 小时前
11.22 脚本 手机termux项目分析(bash)
前端·python·stm32·flask·bash
小南家的青蛙2 小时前
LeetCode面试题 04.06 后继者
算法·leetcode·职场和发展
IT·小灰灰2 小时前
基于Python的机器学习/数据分析环境搭建完全指南
开发语言·人工智能·python·算法·机器学习·数据分析
程序员爱钓鱼2 小时前
Python职业路线规划:从入门到高级开发者的成长指南
后端·python·trae
程序员爱钓鱼2 小时前
Python 编程实战 · 进阶与职业发展:自动化运维(Ansible、Fabric)
后端·python·trae