前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >306. Additive Number

306. Additive Number

原创
作者头像
Michel_Rolle
发布2024-07-12 23:21:12
4981
发布2024-07-12 23:21:12
举报
文章被收录于专栏:LeetCode解题

link

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.

Example 1:

代码语言:javascript
复制
Input: "112358"
Output: true
Explanation: 
The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
代码语言:javascript
复制
func isAdditiveNumber(num string) bool {
    nums := make([]int, len(num))

    for i := 0; i < len(num); i++ {
		nums[i] = int(num[i])-48
	}
    count := 0
    backtrack(nums, nil, &count)

    if count == 0 {
        return false
    }
    return true
}

func backtrack(nums, track []int, count *int) {
    if !judge(track) {
        return 
    }
    if len(nums) == 0 && len(track) >= 3{ 
        *count++
        return 
    }

    for i :=0; i < len(nums); i++ {
        if i!=0 && nums[0] == 0 {
            return
        }

        numscopy := append([]int{}, nums...) 
        trackcopy := append([]int{}, track...)
         
        backtrack(numscopy[i+1:], append(trackcopy, transfer(numscopy[:i+1])) ,count )
    }
}

func judge(track []int) bool {
    
    if len(track) <= 2 {
        return true
    }

    length := len(track)

    if track[length-1] != track[length-2] + track[length-3] {
        return false
    }
    return true
}

func transfer(data []int) int {
    count :=0

    for i:=0; i < len(data); i++ {
        count = count * 10 + data[i]
    }
    return count
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档