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)
相关推荐
一切顺势而行6 分钟前
python 面向对象
开发语言·python
绍兴贝贝1 小时前
代码随想录算法训练营第四十六天|LC647.回文子串|LC516.最长回文子序列|动态规划总结
数据结构·人工智能·python·算法·动态规划·力扣
愚润求学1 小时前
【动态规划】二维的背包问题、似包非包、卡特兰数
c++·算法·leetcode·动态规划
重生之后端学习2 小时前
236. 二叉树的最近公共祖先
java·数据结构·算法·职场和发展·深度优先
___波子 Pro Max.2 小时前
Python参数解析默认True变False
python
橙露2 小时前
面向对象编程思想:Java 与 Python 的封装、继承与多态对比分析
java·开发语言·python
Jia ming2 小时前
《智能法官软件项目》—法条检索模块
python·教学·案例·智能法官软件
LitchiCheng2 小时前
Mujoco 如何添加 Apriltag 并获得相机视野进行识别
人工智能·python·开源
追随者永远是胜利者2 小时前
(LeetCode-Hot100)42. 接雨水
java·算法·leetcode·职场和发展·go
一切尽在,你来2 小时前
LangGraph快速入门
人工智能·python·langchain·ai编程