目录

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)
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
Humbunklung32 分钟前
Sigmoid函数简介及其Python实现
开发语言·python·深度学习·机器学习
麦麦大数据1 小时前
vue+django农产品价格预测和推荐可视化系统[带知识图谱]
vue.js·python·django·知识图谱·推荐算法·价格预测·农业大数据
liwulin05062 小时前
【JAVAFX】实现屏幕指定区域截图,带尺寸显示
服务器·前端·python
大魔王(已黑化)3 小时前
LeetCode —— 572. 另一棵树的子树
c语言·数据结构·c++·算法·leetcode·职场和发展
一个天蝎座 白勺 程序猿3 小时前
Python爬虫(11)Python数据存储实战:深入解析NoSQL数据库的核心应用与实战
开发语言·python·nosql
喜欢吃豆4 小时前
大模型api压力测试
服务器·数据库·人工智能·python·prompt·压力测试
正在走向自律4 小时前
AI数字人:人类身份与意识的终极思考(10/10)
人工智能·python·数字孪生·ai数字人·多模态交互
神奇侠20245 小时前
基于tabula对pdf中多个excel进行识别并转换成word中的优化(四)
python·pdf·word·tabula
serve the people5 小时前
centos上安装python的3.13版本
linux·python·centos
九班长5 小时前
JMeter WebSocket 压测详细步骤(支持 ws+proto 协议)
开发语言·python·网络协议·jmeter·golang