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)
相关推荐
4SAPI6 小时前
多模型请求路由怎么设计?成本、速度和能力如何平衡
人工智能·python·gateway·php
XCDoris8 小时前
郴州logo设计机构
大数据·人工智能·python
gCode Teacher 格码致知8 小时前
Pandas教学-17:Series与Dataframe的关系
开发语言·python·pandas
马良神笔9 小时前
2026 年Rag最近技术前沿总结
后端·python·django
不像程序员的程序媛10 小时前
maven基础
python·pycharm·maven
xiaogai_gai11 小时前
仅查询策略实战:从金蝶云·星空旗舰版定时拉取收料通知单
大数据·数据库·python
benchmark_cc11 小时前
Python 量化系统如何设计统一的数据访问接口:从策略解耦到数据层架构
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
文丑颜不良啊11 小时前
LeetCode51~75题目解析
leetcode
const_qiu11 小时前
第四章 00:开篇 —— 从「会聊天」到「记得住、会干活、能协作」
java·开发语言·人工智能·python
学电子她就能回来吗12 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode