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)
相关推荐
2301_817497334 小时前
自然语言处理(NLP)入门:使用NLTK和Spacy
jvm·数据库·python
TracyCoder1235 小时前
LeetCode Hot100(17/100)——240. 搜索二维矩阵 II
算法·leetcode
weixin_550083155 小时前
QTdesigner配置在pycharm里使用anaconda环境配置安装成功
ide·python·pycharm
强化试剂瓶5 小时前
Silane-PEG8-DBCO,硅烷-聚乙二醇8-二苯并环辛炔技术应用全解析
python·flask·numpy·pyqt·fastapi
钱多多先森5 小时前
【Dify】使用 python 调用 Dify 的 API 服务,查看“知识检索”返回内容,用于前端溯源展示
开发语言·前端·python·dify
有一个好名字5 小时前
力扣-钥匙和房间
算法·leetcode·深度优先
zhougl9965 小时前
Java定时任务实现
java·开发语言·python
ZPC82105 小时前
ROS2 独占内核
人工智能·python·算法·机器人
老鼠只爱大米5 小时前
LeetCode经典算法面试题 #104:二叉树的最大深度(深度优先搜索、广度优先搜索等多种实现方案详细解析)
算法·leetcode·二叉树·dfs·bfs·深度优先搜索·广度优先搜索
爱尔兰极光5 小时前
LeetCode热题100--两数之和
算法·leetcode·职场和发展