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)
相关推荐
Michelle802322 分钟前
24大数据 16-1 函数复习
python
dagouaofei29 分钟前
AI自动生成PPT工具对比分析,效率差距明显
人工智能·python·powerpoint
ku_code_ku32 分钟前
python bert_score使用本地模型的方法
开发语言·python·bert
祁思妙想1 小时前
linux常用命令
开发语言·python
流水落花春去也1 小时前
用yolov8 训练,最后形成训练好的文件。 并且能在后续项目使用
python
LYFlied1 小时前
【每日算法】LeetCode 19. 删除链表的倒数第 N 个结点
算法·leetcode·链表
Serendipity_Carl1 小时前
数据可视化实战之链家
python·数据可视化·数据清洗
小裴(碎碎念版)1 小时前
文件读写常用操作
开发语言·爬虫·python
TextIn智能文档云平台2 小时前
图片转文字后怎么输入大模型处理
前端·人工智能·python
ujainu2 小时前
Python学习第一天:保留字和标识符
python·学习·标识符·保留字