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)
相关推荐
高洁0110 分钟前
大模型-模型压缩:量化、剪枝、蒸馏、二值化 (4)
人工智能·python·深度学习·aigc·transformer
王六岁11 分钟前
# 🐍 前端开发 0 基础学Python小结 Python数据类型使用场景与用途指南
前端·python
luoganttcc16 分钟前
用Python的trimesh库计算3DTiles体积的具体代码示例
开发语言·python·3d
Q741_1471 小时前
C++ 分治 归并排序 归并排序VS快速排序 力扣 912. 排序数组 题解 每日一题
c++·算法·leetcode·归并排序·分治
我狸才不是赔钱货3 小时前
Python的“环境之殇”:从Venv到Conda的终极抉择
开发语言·python·conda
程序员爱钓鱼4 小时前
Python编程实战 - 函数与模块化编程 - 参数与返回值
后端·python·ipython
程序员爱钓鱼4 小时前
Python编程实战 - 函数与模块化编程 - 局部变量与全局变量
后端·python·ipython
jiuri_121510 小时前
Docker使用详解:在ARM64嵌入式环境部署Python应用
python·docker·容器
chenchihwen10 小时前
AI代码开发宝库系列:Function Call
人工智能·python·1024程序员节·dashscope