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)
相关推荐
老纪9 小时前
如何解决OUI图形界面无法调用_xhost与DISPLAY变量设置
jvm·数据库·python
知行合一。。。9 小时前
Python--05--面向对象(继承,多态)
android·开发语言·python
m0_617493949 小时前
PyTorch CUDA设备不可用错误解决方案
人工智能·pytorch·python
小郑加油9 小时前
python学习Day15:综合训练——数据清洗与缺失值补充
开发语言·python·学习
完成大叔9 小时前
Agent入门:用本地模型从零搭建
开发语言·python·langchain
qxwlcsdn10 小时前
CSS如何实现元素镜像翻转_使用transformscalex负值
jvm·数据库·python
2301_8039346110 小时前
mysql如何处理大量重复值索引_mysql索引存储特征分析
jvm·数据库·python
IpdataCloud10 小时前
如何用Python和IP离线库查询IP归属地?获取国家、城市、经纬度的完整代码
开发语言·python·tcp/ip
EnCi Zheng10 小时前
09-斯坦福CS336作业 [特殊字符]
人工智能·pytorch·python·深度学习·神经网络