LeetCode 306. Additive Number C++

本文介绍了一种算法,用于判断一个仅包含数字的字符串是否为加法数。加法数是指该字符串的数字可以形成一个至少包含三个数的加法序列。文章详细解释了如何通过递归回溯的方法实现这一功能,并提供了具体的代码示例。

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

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

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

Approach

1.这道题和842. Split Array into Fibonacci Sequence几乎是一样的,不过这里是没有限制数在32位以内,题目的测试样例应该是在64位以内,它是回溯类题,那么我们就用递归回溯去解决,我们要首先要判断递归式,我们其实不确定每次提取多长的字符串,所以我们的递归式是枚举1~nums.size()-pos范围长度的字符串,pos为当前位置,然后我们还用一个vector装之前提取的字符串(已转化为数字),很明显递归边界就是字符串的终点,即pos==nums.size()的时候,然后我们要判断vector里的数字是否能过组成斐波那契数列,所以我们也将递归返回值设为bool,这样当不能组成斐波那契数列的时候,回溯将某个错误数字剔除。

Code

class Solution {
public:
    string long_max;
    bool isAdditiveNumber(string num) {
        vector<long long> nums;
        long_max = to_string(LLONG_MAX);
        return DFS(nums, num, 0, num.size());
    }
    bool isvalid(vector<long long> &nums) {
        if (nums.size() < 3)return false;
        for (int i = 2; i < nums.size(); i++) {
            long long a = nums[i - 2];
            long long b = nums[i - 1];
            long long c = nums[i];
            if (a + b != c)return false;
        }
        return true;
    }
    bool DFS(vector<long long> &nums, string &str, int pos, int N) {
        if (pos == N) {
            return isvalid(nums);
        }
        for (int i = 1; i <= N - pos; i++) {
            if (str[pos] == '0'&&i > 1)break;
            string sub = str.substr(pos, i);
            if (sub.size() > long_max.size() || sub.size() == long_max.size() && sub.compare(long_max) > 0)break;
            nums.push_back(stoll(sub));
            if ((nums.size()>2 && !isvalid(nums)) || !DFS(nums, str, pos + i, N)) {
                nums.pop_back();
            }
            else {
                return true;
            }
        }
        return false;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值