LeetCode: 306. Additive Number

本文深入解析LeetCode第306题“加性数字”,通过深度优先搜索算法解决字符串中是否存在加性序列的问题。文章提供了解题思路、大数加法实现及AC代码示例。

LeetCode: 306. Additive Number

题目描述

Additive number is a string whose digits can form 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 '0'-'9', write a function to determine if it’s an additive number.

Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Example 1:

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

Example 2:

Input: "199100199"
Output: true
Explanation: The additive sequence is: 1, 99, 100, 199. 
             1 + 99 = 100, 99 + 100 = 199

Constraints:

  • num consists only of digits '0'-'9'.
  • 1 <= num.length <= 35

Follow up:
How would you handle overflow for very large input integers?

解题思路 —— 深度优先搜索

  1. 题目中提到数字可能越界,因此需要自己实现 大数加法
  2. 深度优先搜索遍历所有情况,判断是否存在满足题意的组合。
  3. 需要注意,每个组合的数字不能有前置 0

AC 代码

// 翻转 num
func reverse(num []byte) [] byte{
    for i, j := 0, len(num)-1; i < j; i, j = i+1, j-1 {
        num[i], num[j] = num[j], num[i]
    }
    return num
}

// 计算 lhv + rhv
func addNumber(lhv, rhv string) string {
    var ans []byte
    carry := 0
    
    for i, j := (len(lhv)-1), (len(rhv)-1); i >= 0 || j >= 0 ||
    	carry != 0; i, j = i-1, j-1 {
        
        if i >= 0 { carry += int(lhv[i] - '0') }
        if j >= 0 { carry += int(rhv[j] - '0') }
        
        ans = append(ans, byte(carry % 10) + '0')
        carry /= 10
    } 
    
    return string(reverse(ans))
}

// 判断数组中的元素是否是 "Additive Numbers"
func judge(arr []string) bool {
    if len(arr) < 3 { return false }
    
    for i := 0; i < len(arr) - 2; i++{
        if addNumber(arr[i], arr[i+1]) != arr[i+2] {
            return false
        }
    }
    
    return true
}

// 深度优先搜索查找合适的组合
func dfs(num string, arr[] string) bool {
    if len(num) == 0 {
        return judge(arr)
    }
    
    for i := 1; i <= len(num); i++{
        // 过滤非 ‘0’ 的前置 ‘0’
        if i != 1 && num[0] == '0' { break }
        
        arr = append(arr, num[0:i])
        if dfs(num[i:], arr) {
            return true
        }
        arr = arr[:len(arr)-1]
    }
    
    return false
}

func isAdditiveNumber(num string) bool {
    return dfs(num, []string{})
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值