Leetcode: Additive Number

本文介绍如何使用回溯算法和剪枝技巧来判断一个由数字组成的字符串是否可以形成有效的加法序列,其中每个后续数字都是前两个数字之和。文章详细解释了算法实现过程,并讨论了处理大整数输入时的溢出问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

For example:
"112358" is an additive number because 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
"199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.

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

The method is to use backtracking with pruning,

we handle the case of overflow when using very large input integers by using long

感想:第1,2个数很重要,决定了后面所有的数,所以先把第1,2个数确定出来,再backtracking看能不能走到最后,第1个数起点固定,所以通过定义第1,2个数终点来确定第1,2个数

 1 public class Solution {
 2     public boolean isAdditiveNumber(String num) {
 3         if (num==null || num.length()<3) return false;
 4         int len = num.length();
 5         for (int i=1; i<=len-2; i++) {
 6             if (i>1 && num.charAt(0)=='0') break;
 7             for (int j=i+1; j<=len-1; j++) {
 8                 if (j>i+1 && num.charAt(i)=='0') break;
 9                 int start1=0, start2=i, start3=j;
10                 while (start3 < len) {
11                     long first = Long.parseLong(num.substring(start1, start2));
12                     long second = Long.parseLong(num.substring(start2, start3));
13                     long third = first + second;
14                     if (num.substring(start3).startsWith(String.valueOf(third))) {
15                         start1 = start2;
16                         start2 = start3;
17                         start3 = start3 + String.valueOf(third).length();
18                     }
19                     else break;
20                 }
21                 if (start3 == len) return true;
22             }
23         }
24         return false;
25     }
26 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值