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)
相关推荐
隔壁大炮2 小时前
MNE-Python 第9天学习笔记:源定位基础
python·eeg·mne·脑电数据处理
Daydream.V3 小时前
Python Flask超全入门实战教程|从零基础到项目部署
大数据·python·flask
浅念-3 小时前
LeetCode 回溯算法题——综合练习
数据结构·c++·算法·leetcode·职场和发展·深度优先·dfs
databook4 小时前
Manim物理模拟:别自己写欧拉了!
python·数学·动效
圣保罗的大教堂4 小时前
leetcode 61. 旋转链表 中等
leetcode
香蕉鼠片5 小时前
Python进阶学习
开发语言·python
亚亚的学习和分享5 小时前
python练习:人生模拟器(简易版)
python
全糖可乐气泡水6 小时前
Codex适配国产信创环境安装部署与技术适配全解析
开发语言·git·python·算法·百度
LeocenaY6 小时前
搜集的一些测开面试题
开发语言·python
嗝o゚6 小时前
昇腾CANN ge 仓的图优化 Pass:哪些 Pass 真正影响推理性能
pytorch·python·深度学习·cann·ge-pass