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)
相关推荐
CLX050511 分钟前
怎样设置外键的更新级联操作_ON UPDATE CASCADE配置
jvm·数据库·python
Gerardisite13 分钟前
企微批量群发消息指南:用 QiWe 省掉人工操作
java·python·机器人·企业微信
zjy2777727 分钟前
SQL Server如何实现编写表与字段注释_Navicat兼容操作步骤
jvm·数据库·python
m0_7020365333 分钟前
CSS移动端实现响应式导航菜单_利用媒体查询切换显示隐藏状态
jvm·数据库·python
m0_5967490935 分钟前
Go语言怎么用Jaeger_Go语言Jaeger链路追踪教程【实用】
jvm·数据库·python
2501_9010064736 分钟前
Golang Gin如何定义路由和路由组_Golang Gin路由教程【实用】
jvm·数据库·python
m0_463672201 小时前
golang如何实现群聊功能_golang群聊功能实现策略
jvm·数据库·python
_376271531 小时前
如何利用 Provide 注入 API 实例?解决组件库依赖全局接口痛点
jvm·数据库·python
2401_850491651 小时前
如何用 keys 与 values 分别提取 Map 的所有键或所有值
jvm·数据库·python
天天进步20151 小时前
Python全栈项目实战:基于深度学习的语音合成(TTS)系统
开发语言·python·深度学习