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)
相关推荐
DN20201 小时前
AI销售:从不迟到早退,永远秒回,您的忠实员工
人工智能·python
编程之升级打怪1 小时前
Python的图形框架tkinter使用案例
python
liu****2 小时前
3.RNN及其变体
人工智能·python·rnn·深度学习
大江东去浪淘尽千古风流人物3 小时前
【Sensor】IMU传感器选型车轨级 VS 消费级
人工智能·python·算法·机器学习·机器人
wangwangmoon_light3 小时前
1.2 LeetCode总结(线性表)_双指针
算法·leetcode·职场和发展
重生之后端学习3 小时前
114. 二叉树展开为链表
java·数据结构·算法·链表·职场和发展·深度优先
码农小韩4 小时前
AIAgent应用开发——DeepSeek分析(一)
人工智能·python·深度学习·agent·强化学习
学Linux的语莫4 小时前
skills的使用
java·数据库·python
Bear on Toilet4 小时前
BFS_FloodFill_46 . 腐烂的橘子问题
数据结构·c++·算法·leetcode·宽度优先
样例过了就是过了4 小时前
LeetCode热题100 找到字符串中所有字母异位词
算法·leetcode