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, 3is 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?

Credits:
Special thanks to @jeantimex for adding this problem and creating all test cases.

这道题定义了一种加法数,就是至少含有三个数字,除去前两个数外,每个数字都是前面两个数字的和,题目中给了许多例子,也限定了一些不合法的情况,比如两位数以上不能以0开头等等,让我们来判断一个数是否是加法数。目光犀利的童鞋应该一眼就能看出来,这尼玛不就是斐波那契数组么,跟另一道 Split Array into Fibonacci Sequence 简直不要太像啊。只不过那道题要返回一种组合方式,而这道题只是问能否拆成斐波那契数列。

开始我还想是否能用动态规划来解,可是发现不会写状态转移方程,只得作罢。其实这题可用Brute Force的思想来解,我们让第一个数字先从一位开始,第二个数字从一位,两位,往高位开始搜索,前两个数字确定了,相加得到第三位数字,三个数组排列起来形成一个字符串,和原字符串长度相比,如果小于原长度,那么取出上一次计算的第二个和第三个数,当做新一次计算的前两个数,用相同的方法得到第三个数,再加入当前字符串,再和原字符串长度相比,以此类推,直到当前字符串长度不小于原字符串长度,比较两者是否相同,相同返回true,不相同则继续循环。如果所有情况都遍历完了还是没有返回true,则说明不是Additive Number,返回false,参见代码如下:

解法一:

class Solution {
public:
bool isAdditiveNumber(string num) {
for (int i = ; i < num.size(); ++i) {
string s1 = num.substr(, i);
if (s1.size() > && s1[] == '') break;
for (int j = i + ; j < num.size(); ++j) {
string s2 = num.substr(i, j - i);
long d1 = stol(s1), d2 = stol(s2);
if ((s2.size() > && s2[] == '')) break;
long next = d1 + d2;
string nextStr = to_string(next);
if (nextStr != num.substr(j, nextStr.length())) continue; // optimization here
string allStr = s1 + s2 + nextStr;
while (allStr.size() < num.size()) {
d1 = d2;
d2 = next;
next = d1 + d2;
nextStr = to_string(next);
allStr += nextStr;
}
if (allStr == num) return true;
}
}
return false;
}
};

此题还有递归解法,博主最先尝试的是跟那道 Split Array into Fibonacci Sequence 一样的递归方法,虽然这道题不用返回组合方式,但是我们仍可以使用一样的递归来做,只不过这里的结果res是一个布尔型的全局变量,当我们找到一组符合题意的组合了之后,就将结果res设置为true,这样一旦再进入递归函数时,只要res为true了,就直接返回即可。之后的部分就基本相同了,可以参见 Split Array into Fibonacci Sequence  中的讲解,注意稍有不同的地方是,这里拆分出来的数字是可以超过整型int范围的,但是貌似不会超过长整型long的范围,所以我们可以加一个检测str的长度大于19就break,因为long的十进制数长度是19位,参见代码如下:

解法二:

class Solution {
public:
bool isAdditiveNumber(string num) {
bool res = false;
vector<long> out;
helper(num, , out, res);
return res;
}
void helper(string& num, int start, vector<long>& out, bool& res) {
if (res) return;
if (start >= num.size()) {
if (out.size() >= ) res = true;
return;
}
for (int i = start; i < num.size(); ++i) {
string str = num.substr(start, i - start + );
if ((str.size() > && str[] == '') || str.size() > ) break;
long curNum = stol(str), n = out.size();
if (out.size() >= && curNum != out[n - ] + out[n - ]) continue;
out.push_back(curNum);
helper(num, i + , out, res);
out.pop_back();
}
}
};

由于这道题并不需要我们返回具体的组合方式,所以也可以不使用上面的写法,而是不停的用当前的两个数,去拼后面的数字,一旦拼不出来了,直接返回false。跟解法一类似,首先用两个for循环来确定前两个数字,然后将后面的整体提取出来,和当前的两个数字一起调用递归,若递归返回true了,则直接返回true,否则继续遍历。

在递归函数中,还是首先检验是否存在leading zeros,然后将 num1 和 num2 分别转为长整型long,相加后再转回字符串,存入sumStr,这时候看sumStr是否和num相等,是的话直接返回true。否则再来检验,若sumStr的长度大于等于num了,返回false,或者在num中取跟sumStr长度相等的子串,若不等于sumStr,说明无法拼出来,也返回false。若都没返回的话,就再次调用递归,不过这次num要去掉和sumStr长度相等的子串,留下后面的部分,此时带入递归的两个数字要变成 num2 和 sumStr,继续跟后面的比较,参见代码如下:

解法三:

class Solution {
public:
bool isAdditiveNumber(string num) {
for (int i = ; i < num.size(); ++i) {
string s1 = num.substr(, i);
if (s1.size() > && s1[] == ) break;
for (int j = i + ; j < num.size(); ++j){
string s2 = num.substr(i, j - i);
if (s2.size() > && s2[] == ) break;
if(helper(num.substr(j), s1, s2)) return true;
}
}
return false;
}
bool helper(string num, string num1, string num2){
if ((num1.size() > && num1[] == '') || (num2.size() > && num2[] == '')) return false;
string sumStr = to_string(stol(num1) + stol(num2));
if (sumStr == num) return true;
if (sumStr.size() >= num.size() || num.substr(, sumStr.size()) != sumStr) return false;
return helper(num.substr(sumStr.size()), num2, sumStr);
}
};

题目中有个 follow up 说是让我们handle超大整数的溢出情况,那么我们想,上面的解法中哪块可能溢出啊,当然只有将子串转为长整型long的时候,假如此时字符串特别长,甚至超出了长整型的范围,那么我们就不能用stol了,此时就不能转换了,那么我们只能强行将两个字符串相加了,这里用的又是另外一道题目 Add Strings 的知识点了,这样我们就完美的避开了可能溢出的情况了,参见代码如下:

解法四:

// Follow up, handle overflow for very large input integers.
class Solution {
public:
bool isAdditiveNumber(string num) {
for (int i = ; i < num.size(); ++i) {
string s1 = num.substr(, i);
if (s1.size() > && s1[] == ) break;
for (int j = i + ; j < num.size(); ++j){
string s2 = num.substr(i, j - i);
if (s2.size() > && s2[] == ) break;
if(helper(num.substr(j), s1, s2)) return true;
}
}
return false;
}
bool helper(string num, string num1, string num2){
if ((num1.size() > && num1[] == '') || (num2.size() > && num2[] == '')) return false;
string sumStr = add(num1, num2);
if (sumStr == num) return true;
if (sumStr.size() >= num.size() || num.substr(, sumStr.size()) != sumStr) return false;
return helper(num.substr(sumStr.size()), num2, sumStr);
}
string add(string num1, string num2) {
string res;
int i = (int)num1.size() - , j = (int)num2.size() - , carry = ;
while (i >= || j >= ) {
int val1 = (i >= ) ? (num1[i--] - '') : ;
int val2 = (j >= ) ? (num2[j--] - '') : ;
int sum = val1 + val2 + carry;
res.push_back(sum % + '');
carry = sum / ;
}
if (carry) res.push_back(carry + '');
reverse(res.begin(), res.end());
return res;
}
};

类似题目:

Add Strings

Split Array into Fibonacci Sequence

参考资料:

https://leetcode.com/problems/additive-number/

https://leetcode.com/problems/additive-number/discuss/75567/Java-Recursive-and-Iterative-Solutions

https://leetcode.com/problems/additive-number/discuss/75704/My-Simple-C%2B%2B-Non-recursion-Solution

https://leetcode.com/problems/additive-number/discuss/75576/0ms-concise-C%2B%2B-solution-(perfectly-handles-the-follow-up-and-leading-0s)

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Additive Number 加法数的更多相关文章

  1. 306 Additive Number 加法数

    Additive number is a string whose digits can form additive sequence.A valid additive sequence should ...

  2. [LeetCode] Additive Number

    Af first I read the title as "Addictive Number". Anyway, this problem can be solved elegan ...

  3. LeetCode(306) Additive Number

    题目 Additive number is a string whose digits can form additive sequence. A valid additive sequence sh ...

  4. 【LeetCode】306. Additive Number 解题报告(Python)

    [LeetCode]306. Additive Number 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http: ...

  5. 【刷题-LeetCode】306. Additive Number

    Additive Number Additive number is a string whose digits can form additive sequence. A valid additiv ...

  6. Leetcode 306. Additive Number

    Additive number is a string whose digits can form additive sequence. A valid additive sequence shoul ...

  7. [LeetCode] 306. Additive Number [Medium]

    306. Additive Number class Solution { private: string stringAddition(string &a, string &b) { ...

  8. 【LeetCode】306. Additive Number

    题目: Additive number is a string whose digits can form additive sequence. A valid additive sequence s ...

  9. 306. Additive Number

    题目: Additive number is a string whose digits can form additive sequence. A valid additive sequence s ...

随机推荐

  1. 移动端web开发的那些坑

    1.为非a列表项添加触感样式 通过js注册touchstart和touchend事件,添加触感class的方式, 有个坑,低版本的Android浏览器,经常触发不到touchend,需要再额外注册一个 ...

  2. PHP之提取多维数组指定列的方法

    前言:有时候在开发中会遇到这样的问题,我们需要把有规律的多维数组按照纵向(列)取出,有下面的方法可用: 我们将拿下面的数组来处理: $arr = array( '0' => array('id' ...

  3. Autofac 组件、服务、自动装配 《第二篇》

    一.组件 创建出来的对象需要从组件中来获取,组件的创建有如下4种(延续第一篇的Demo,仅仅变动所贴出的代码)方式: 1.类型创建RegisterType AutoFac能够通过反射检查一个类型,选择 ...

  4. filter 过滤器(监听)

    Filter 过滤器 1.简介 Filter也称之为过滤器,它是Servlet技术中最实用的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, ...

  5. MySQL的简单使用和JDBC示例

    MySql是关系型数据库管理系统(RDBMS),所谓的"关系型"可以把它当作是"表格"概念,事实上,一个关系型数据库由一个或数个表格组成. MySQL所使用的S ...

  6. 实现文字自动横移--- jquery尺寸相关函数

    效果图: 一实现文字自动横移 <style type="text/css"> #demo {overflow:scroll;width:740px; } #indemo ...

  7. 使用tomcat manager 管理和部署项目

    在部署tomcat项目的时候,除了把war文件直接拷贝到tomcat的webapp目录下,还有一种方法可以浏览器中管理和部署项目,那就是使用tomcat manager. 默认情况下,tomcat m ...

  8. asp.net获取数据库的连接字符串

    1.添加引用 using System.Configuration; 2.代码 string strConnectionString=ConfigurationManager.AppSettings[ ...

  9. 分享一个ReactiveCocoa的很好的教程(快速上手)

    这是我看到的比较全而且讲的很好的文章 https://www.raywenderlich.com/62796/reactivecocoa-tutorial-pt1 https://www.raywen ...

  10. SQL Server快速查询某张表的当前行数

    传统做法可能是select count(1) 但是往往会比较慢.推荐如下做法: ) CurrentRowCount FROM sys.sysindexes WHERE id = OBJECT_ID(' ...