Additive Number

本文介绍了一种通过回溯算法来判断一个字符串是否为加法数序列的方法。加法数序列是指一个由数字组成的字符串,其中除前两个数字外,每个后续数字都是前两个数字之和。文章详细解释了如何实现这一判断逻辑,并提供了具体的代码示例。

[leetcode]Additive Number

链接:https://leetcode.com/problems/additive-number/description/

Question

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

Solution

class Solution {
public:
  string num;
  typedef long long int ll;
  bool dfs(int left, vector<ll> ans) {
    if (left == num.size() && ans.size() >= 3) return true;
    for (int gap = 1; left+gap <= num.size() && gap <= num.size()/2; gap++) {
      string sub = num.substr(left, gap);
      if (sub[0] == '0' && sub.size() > 1) continue;
      ll sub_num = stol(sub.c_str());
      if (ans.size() <= 1) {
        ans.push_back(sub_num);
        bool success = dfs(left+gap, ans);
        ans.pop_back();
        if (success) return true;
      } else {
        ll first = ans[ans.size()-2];
        ll second = ans[ans.size()-1];
        if (first+second == sub_num) {
          ans.push_back(sub_num);
          bool success = dfs(left+gap, ans);
          ans.pop_back();
          if (success) return true;
        } else if (first+second < sub_num) break;
      }
    }
    return false;
  }

  bool isAdditiveNumber(string num) {
    this->num = num;
    return dfs(0, vector<ll>());
  }
};

思路:类似之前的一道判断是不是斐波那契数列的题,常规回溯;-)注意要判断不能有前置的0,巧妙的地方在于gap。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值