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)
相关推荐
CHANG_THE_WORLD6 分钟前
C++ vs Python 参数传递方式对比
java·c++·python
好易学·数据结构1 小时前
可视化图解算法72:斐波那契数列
数据结构·算法·leetcode·动态规划·力扣·牛客网
梁正雄1 小时前
10、Python面向对象编程-2
开发语言·python
Jo乔戈里1 小时前
Python复制文件到剪切板
开发语言·python
小鱼儿亮亮2 小时前
SSE传输方式的MCP服务器创建流程
python·mcp
B站_计算机毕业设计之家2 小时前
python招聘数据 求职就业数据可视化平台 大数据毕业设计 BOSS直聘数据可视化分析系统 Flask框架 Echarts可视化 selenium爬虫技术✅
大数据·python·深度学习·考研·信息可视化·数据分析·flask
子夜江寒2 小时前
Python 学习-Day9-pandas数据导入导出操作
python·学习·pandas
码农很忙2 小时前
让复杂AI应用构建像搭积木:Spring AI Alibaba Graph深度指南与源码拆解
开发语言·人工智能·python
CoderYanger2 小时前
动态规划算法-子数组、子串系列(数组中连续的一段):21.乘积最大子数组
开发语言·算法·leetcode·职场和发展·动态规划·1024程序员节
CoderYanger2 小时前
A.每日一题——3432. 统计元素和差值为偶数的分区方案
java·数据结构·算法·leetcode·1024程序员节