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)
相关推荐
m0_748920361 分钟前
Oracle默认端口被占用如何连接_修改端口号操作教程
jvm·数据库·python
YummyJacky2 分钟前
Hermes Agent自进化的实现方式
人工智能·python
qq_342295828 分钟前
Redis怎样按照距离远近排序展示_通过GEORADIUS的ASC参数进行Geo排序
jvm·数据库·python
2201_7610405914 分钟前
C#比较两个二进制文件的差异 C#如何实现一个二进制diff工具
jvm·数据库·python
Csvn21 分钟前
🌟 LangChain 30 天保姆级教程 · Day 23|Agent 进阶实战!Function Calling + 自动 Tool 注册,打造会“动
python·langchain
Csvn21 分钟前
🌟 LangChain 30 天保姆级教程 · Day 22|长文档处理三剑客!MapReduce、Refine、Map-Rerank,让 AI 消化整本手册
python·langchain
John.Lewis33 分钟前
Python小课(1)认识Python
开发语言·python
Polar__Star35 分钟前
SQL中如何实现特定顺序的查询:CASE WHEN自定义排序
jvm·数据库·python
u01091476042 分钟前
mysql如何配置监听IP_mysql bind-address多地址设置
jvm·数据库·python
a9511416421 小时前
如何配置RMAN使用第三方备份软件接口_NetBackup或Commvault的MML层整合
jvm·数据库·python