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)
相关推荐
Once_day7 小时前
代码训练LeetCode(21)跳跃游戏2
算法·leetcode
Amo Xiang8 小时前
Python 解释器安装全攻略(适用于 Linux / Windows / macOS)
linux·windows·python·环境安装
程序员杰哥8 小时前
接口自动化测试之pytest 运行方式及前置后置封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
浩皓素8 小时前
用Python开启游戏开发之旅
python
德先生&赛先生8 小时前
LeetCode-934. 最短的桥
算法·leetcode·职场和发展
hello kitty w8 小时前
Python学习(6) ----- Python2和Python3的区别
开发语言·python·学习
互联网杂货铺10 小时前
功能测试、性能测试、安全测试详解
自动化测试·软件测试·python·功能测试·测试工具·性能测试·安全性测试
土豆杨62610 小时前
隐藏层-机器学习
python·机器学习
Dxy123931021611 小时前
DrissionPage调试工具:网页自动化与数据采集的革新利器
爬虫·python·drissionpage