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)
相关推荐
2501_907136822 分钟前
基于Python+QT6的移动硬盘弹出工具
python·软件需求
VT.馒头5 分钟前
【力扣】2625. 扁平化嵌套数组
前端·javascript·算法·leetcode·职场和发展·typescript
2501_9071368231 分钟前
python 界面元素控件库工具,可以看到python的可视控件和使用方法
python·软件需求
2301_7657031434 分钟前
开发一个简单的Python计算器
jvm·数据库·python
yj155835 分钟前
客厅阳台改卧室需要注意什么?
python
boss-dog38 分钟前
关于强化学习入门理解和示例
python·强化学习
一只理智恩1 小时前
筹备计划·江湖邀请令!!!
python·langchain
Sagittarius_A*1 小时前
角点检测:Harris 与 Shi-Tomasi原理拆解【计算机视觉】
图像处理·人工智能·python·opencv·计算机视觉
进击的小头1 小时前
陷波器实现(针对性滤除特定频率噪声)
c语言·python·算法
LitchiCheng1 小时前
Mujoco 开源机械臂 RL 强化学习避障、绕障
人工智能·python·开源