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)
相关推荐
大数据魔法师30 分钟前
Python 网络请求库 curl_cffi:从入门到实战,如何规避网站指纹检测
python·数据分析
中电华星32 分钟前
专业的工业电源公司
网络·python
databook1 小时前
用统计检验来确定“重要特征”
python·机器学习·scikit-learn
0566461 小时前
Python高级——解释器执行原理与虚拟环境工程化实战
开发语言·python
weixin_435776111 小时前
2026年长沙托育vi设计从风格定位到元素运用的设计方法
linux·运维·服务器·python
梦想三三1 小时前
LangChain RAG PDF 智能问答实战:用 Streamlit 构建本地知识库(完整代码)
人工智能·python·langchain·大模型·rag
星轨初途2 小时前
LeetCode 热题 100——day2 字母异位词分组
c++·算法·leetcode
电化学仪器白超2 小时前
禹衡光栅长度计精度评测:基于国标0级氧化锆量块的校正与数据分析
python·单片机·嵌入式硬件·物联网·自动化
小玮看世界3 小时前
[Python]自动驾驶感知与决策练习题 (1-10)
开发语言·python·自动驾驶
Ming_studying3 小时前
Python + SQLite FTS5 构建本地文档全文搜索器:增量索引、中文检索与高亮
jvm·数据库·python·sqlite