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)
相关推荐
Stream_Silver6 分钟前
【安装与配置Anaconda步骤,包含卸载重装】
python·conda
ai_top_trends6 分钟前
AI 生成 PPT 工具横评:效率、质量、稳定性一次说清
人工智能·python·powerpoint
天天睡大觉9 分钟前
Python学习9
开发语言·python·学习
2301_7973122610 分钟前
学习Java39天
开发语言·python·学习
曲幽12 分钟前
FastAPI搭档Pydantic:从参数验证到数据转换的全链路实战
python·fastapi·web·path·field·query·pydantic·basemodel·response_model
程序员-King.24 分钟前
day131—链表—反转链表Ⅱ(区域反转)(LeetCode-92)
leetcode·链表·贪心算法
Halo_tjn26 分钟前
基于Java的相关知识点
java·开发语言·windows·python·算法
ghostmen29 分钟前
SpringBoot + Vue 实现 Python 在线调试器 - 技术方案文档
java·python·vue·springboot
圣保罗的大教堂32 分钟前
leetcode 2943. 最大化网格图中正方形空洞的面积 中等
leetcode
阳光九叶草LXGZXJ1 小时前
达梦数据库-学习-43-定时备份模式和删除备份(Python+Crontab)
linux·运维·开发语言·数据库·python·学习