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)
相关推荐
老师好,我是刘同学3 小时前
Python执行命令并保存输出到文件
python
啵啵鱼爱吃小猫咪5 小时前
机械臂阻抗控制github项目-mujoco仿真
开发语言·人工智能·python·机器人
MaximusCoder5 小时前
等保测评命令——Centos Linux
linux·运维·经验分享·python·安全·centos
yunyun321235 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
m0_662577975 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
songyuc5 小时前
【PyTorch】感觉`CrossEntropyLoss`和`BCELoss`很类似,为什么它们接收labels的shape常常不一样呢?
人工智能·pytorch·python
ℳ๓₯㎕.空城旧梦5 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
浩子智控6 小时前
python程序打包的文件地址处理
开发语言·python·pyqt
Jackey_Song_Odd6 小时前
Part 1:Python语言核心 - 序列与容器
开发语言·windows·python
m0_662577976 小时前
Python迭代器(Iterator)揭秘:for循环背后的故事
jvm·数据库·python