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)
相关推荐
huwei8536 小时前
python设计通用表格类 带右键菜单
开发语言·windows·python
计算机毕业编程指导师6 小时前
【计算机毕设选题】基于Spark的拉勾网招聘数据分析系统源码,Python+Django全流程
大数据·hadoop·python·spark·django·招聘·拉勾网
duyinbi75176 小时前
TOOD_R50_FPN_Anchor-Based_1x_COCO_列车悬挂部件检测分类实战
python
努力学算法的蒟蒻7 小时前
day59(1.18)——leetcode面试经典150
算法·leetcode·职场和发展
学习3人组7 小时前
大模型轻量化调优(昇腾平台方向)岗位技术名词拆解
人工智能·python
知乎的哥廷根数学学派7 小时前
基于物理引导和不确定性量化的轻量化神经网络机械退化预测算法(Python)
人工智能·pytorch·python·深度学习·神经网络·算法·机器学习
程序员-King.7 小时前
day146—递归—验证二叉搜索树(LeetCode-98)
算法·leetcode·二叉树·递归
iAkuya7 小时前
(leetcode)力扣100 45二叉树的右视图(dfs,bfs)
leetcode·深度优先·宽度优先
xj7573065337 小时前
Django 面试常见问题
python·面试·django
a努力。7 小时前
得物Java面试被问:Netty的ByteBuf引用计数和内存释放
java·开发语言·分布式·python·面试·职场和发展