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)
相关推荐
FriendshipT几秒前
Ultralytics:解读CBLinear模块
人工智能·pytorch·python·深度学习·目标检测
AI开发发烧友24 分钟前
LangGraph多Agent协作实战:以物流售前场景为例的5 Agent工作流设计
python
码云骑士28 分钟前
70-多Agent协作-CrewAI-AutoGen-角色分工与信息传递协议
python
Hachi被抢先注册了1 小时前
Skills总结
python
用户0332126663671 小时前
使用 Python 在 PowerPoint 中创建折线图和条形图
python
benchmark_cc1 小时前
如何用 Python 进行多周期 K 线合成与时区对齐?基于 QuantDash 与 Pandas 的量化数据清洗实战(附 GitHub 源码)
开发语言·python·github·盯盘·pandas·quantdash·量化数据
tkevinjd1 小时前
力扣148-排序链表
算法·leetcode·链表
不如语冰1 小时前
AI大模型入门-参数的传递
数据结构·人工智能·pytorch·python
用户6760840656171 小时前
GraphBLAS_01_图的稀疏表示
python
小陈工1 小时前
第7篇:Django框架核心原理与实战深度解析(下)
后端·python·面试