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)
相关推荐
程序员miki几秒前
Redis核心命令以及技术方案参考文档(分布式锁,缓存业务逻辑)
redis·分布式·python·缓存
热爱生活的五柒2 分钟前
两个电脑(windows和linux之间)如何快速传输文件(亲测可用,方便快捷)
python·共享文件夹
洋生巅峰10 分钟前
股票爬虫实战解析
爬虫·python·mysql
失心疯_202313 分钟前
Pycharm打开Terminal终端无法自动进入项目虚拟环境
ide·python·pycharm·虚拟环境·terminal
BoBoZz1915 分钟前
Vol 建一个 3D 隐式函数体积数据
python·vtk·图形渲染·图形处理
倔强的小石头_15 分钟前
Python 从入门到实战(十三):Flask + 数据库(让 Web 应用支持数据持久化与多人协作)
数据库·python·flask
jiayong2318 分钟前
AI应用领域编程语言选择指南:Java vs Python vs Go
java·人工智能·python
_illusion_23 分钟前
反向传播的人生哲学:深度复盘的力量
人工智能·python·机器学习
博大世界25 分钟前
Python打包成exe文件方法
开发语言·python
算法与编程之美25 分钟前
解决tensor的shape不为1,如何转移到CPU的问题
人工智能·python·深度学习·算法·机器学习