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)
相关推荐
郝学胜-神的一滴23 分钟前
Python中一切皆对象:深入理解Python的对象模型
开发语言·python·程序人生·个人开发
烤汉堡1 小时前
Python入门到实战:post请求和响应
python·html
夫唯不争,故无尤也1 小时前
Python广播机制:张量的影分身术
开发语言·python
sin_hielo1 小时前
leetcode 1930
算法·leetcode
流浪猪头拯救地球1 小时前
利用 Python 解密 / 加密 PDF 文件
python·pdf·php
花开花富贵2 小时前
多语言的爱意告白
python
百锦再3 小时前
第21章 构建命令行工具
android·java·图像处理·python·计算机视觉·rust·django
努力学算法的蒟蒻3 小时前
day17(11.18)——leetcode面试经典150
算法·leetcode·面试
蒋星熠3 小时前
常见反爬策略与破解反爬方法:爬虫工程师的攻防实战指南
开发语言·人工智能·爬虫·python·网络安全·网络爬虫
不爱编程爱睡觉3 小时前
代码随想录算法训练营第二十八天 | 动态规划算法基础、 LeetCode509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法·leetcode·动态规划·代码随想录