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)
相关推荐
@––––––4 小时前
力扣hot100—系列4-贪心算法
算法·leetcode·贪心算法
墨理学AI4 小时前
一文学会一点python数据分析-小白原地进阶(mysql 安装 - mysql - python 数据分析 - 学习阶段梳理)
python·mysql·数据分析
数研小生4 小时前
亚马逊商品列表API详解
前端·数据库·python·pandas
独好紫罗兰4 小时前
对python的再认识-基于数据结构进行-a005-元组-CRUD
开发语言·数据结构·python
jianghua0014 小时前
Python中的简单爬虫
爬虫·python·信息可视化
喵手4 小时前
Python爬虫实战:针对Python官网,精准提取出每一个历史版本的版本号、发布日期以及对应的文档/详情页链接等信息,并最终清洗为标准化的CSV文件!
爬虫·python·爬虫实战·零基础python爬虫教学·python官方数据采集·采集历史版本版本号等信息·导出csv文件
im_AMBER5 小时前
Leetcode 115 分割链表 | 随机链表的复制
数据结构·学习·算法·leetcode
databook5 小时前
像搭积木一样思考:数据科学中的“自下而上”之道
python·数据挖掘·数据分析
luoluoal5 小时前
基于python的医疗问句中的实体识别算法的研究(源码+文档)
python·mysql·django·毕业设计·源码
夏鹏今天学习了吗5 小时前
【LeetCode热题100(99/100)】柱状图中最大的矩形
算法·leetcode·职场和发展