题目:

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?

提示:

这题在题目中已经给出了一个重要的提示揭示了题目中的一个小陷阱,由于输入是字符串,所以我们在做加法的时候可能会溢出,所以需要实现一个基于字符串的加法,比如像下面这样:

string add(string a, string b) {
int i = a.length() - , j = b.length() - , carry = ;
string res;
while (i >= || j >= ) {
int digit = carry + (i >= ? a[i--] - '' : ) + (j >= ? b[j--] - '' : );
res.push_back(digit % + '');
carry = digit / ;
}
if (carry) {
res.push_back(carry + '');
}
reverse(res.begin(), res.end());
return res;
}

然后就是要想出算法的整体解决思路,我的思路就是递归求解,一旦发现一个成功的Additive Number就返回true。这里循环内的终止条件就尤为重要了,若可以切割掉一些显然不成立的分支,那么算法的速度就能得到提升。这里的思路是这样的:

  • 由于给定的字符串需要划分成至少三个数字,所以第一个数字的长度最多等于字符串长度的一半,因为整除是向下取整,所以取等号:
  • for (int i = ; i <= num.size() / ; ++i)
  • 因为是求和,所以第二个字符串的长度只能最多为剩下字符串长度的一半:
  • for (int j = ; j  <= (num.size()-i)/; ++j)

最后就是递归函数中的终止条件了,这些都比较简单,详见代码。

代码:

class Solution {
public:
bool isAdditiveNumber(string num) {
for (int i = ; i <= num.size() / ; ++i) {
for (int j = ; j <= (num.size()-i)/; ++j) {
if (check(num.substr(, i), num.substr(i, j), num.substr(i+j))) {
return true;
}
}
}
return false;
} bool check(string a, string b, string c) {
if (a.size() > && a[] == '' || b.size() > && b[] == '') {
return false;
}
string r = add(a, b);
if (r == c) {
return true;
}
if (r.size() >= c.size()) {
return false;
}
for (int i = ; i < r.size(); ++i) {
if (r[i] != c[i]) {
return false;
}
}
return check(b, r, c.substr(r.size()));
} string add(string a, string b) {
int i = a.length() - , j = b.length() - , carry = ;
string res;
while (i >= || j >= ) {
int digit = carry + (i >= ? a[i--] - '' : ) + (j >= ? b[j--] - '' : );
res.push_back(digit % + '');
carry = digit / ;
}
if (carry) {
res.push_back(carry + '');
}
reverse(res.begin(), res.end());
return res;
}
};

【LeetCode】306. Additive Number的更多相关文章

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

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

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

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

  3. 【LeetCode】375. Guess Number Higher or Lower II 解题报告(Python)

    [LeetCode]375. Guess Number Higher or Lower II 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  4. 【LeetCode】137. Single Number II 解题报告(Python)

    [LeetCode]137. Single Number II 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/single- ...

  5. 【LeetCode】452. Minimum Number of Arrows to Burst Balloons 解题报告(Python)

    [LeetCode]452. Minimum Number of Arrows to Burst Balloons 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https ...

  6. 【LeetCode】65. Valid Number

    Difficulty: Hard  More:[目录]LeetCode Java实现 Description Validate if a given string can be interpreted ...

  7. 【Leetcode】179. Largest Number

    Given a list of non negative integers, arrange them such that they form the largest number. For exam ...

  8. 【leetcode】1189. Maximum Number of Balloons

    题目如下: Given a string text, you want to use the characters of text to form as many instances of the w ...

  9. 【LeetCode】264. Ugly Number II 解题报告(Java & Python)

    标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ https://leetcode.com/prob ...

随机推荐

  1. [UWP]实用的Shape指南

    在UWP UI系统中,使用Shape是绘制2D图形最简单的方式,小到图标,大到图表都用到Shape的派生类,可以说有举足轻重的地位.幸运的是从Silverlight以来Shape基本没有什么大改动,简 ...

  2. 蚂蚁金服新一代数据可视化引擎 G2

    新公司已经呆了一个多月,目前着手一个数据可视化的项目,数据可视化肯定要用到图形库如D3.Highcharts.ECharts.Chart等,经决定我的这个项目用阿里旗下蚂蚁金服所开发的G2图表库. 官 ...

  3. 深入理解Java常用类----String(二)

    上篇介绍了String类的构造器,获取内部属性等方法,最后留下了最常用的局部操作函数没有介绍,本篇将接着上篇内容,从这些最常见的函数的操作说起,看看我们日常经常使用的这些方法的内部是怎么实现的.第一个 ...

  4. 浏览器如何生成URL

    点击页面中的链接,浏览器会根据源码中相对URL路径作不同的处理: (1)有协议名称,但没有域名信息 对于这种形式的URL,它的协议,路径,查询字符串和片段ID都以它自身为准,但域名信息的部分,以引用它 ...

  5. JS代码整洁随笔

    // 之前都是这么写:使用undefined和null来检测一个属性是否存在 if (obj['name'] !== undefined) { console.log('name属性存在'); // ...

  6. 第 15 章 可扩展性设计之 Cache 与 Search 的利用

    前言: 前面章节部分所分析的可扩展架构方案,基本上都是围绕在数据库自身来进行的,这样是否会使我们在寻求扩展性之路的思维受到“禁锢”,无法更为宽广的发散开来.这一章,我们就将跳出完全依靠数据库自身来改善 ...

  7. struts2.1.6教程四_2、ActionContext 、ValueStack 、Stack Context

    ActionContext 一次Action调用都会创建一个ActionContext 调用:ActionContext context = ActionContext.getContext() Va ...

  8. JVM学习笔记三:垃圾收集器与内存分配策略

    内存回收与分配重点关注的是堆内存和方法区内存(程序计数器占用小,虚拟机栈和本地方法栈随线程有相同的生命周期). 一.判断对象是否存活? 1. 引用计数算法 优势:实现简单,效率高. 致命缺陷:无法解决 ...

  9. 初入计算机图形学(二):对bidirectional path tracing的一些困惑

    本人水平有限,若有错误也请指正~ 前文提及了光线追踪的一些常用手法,但是其中path tracing的实现最为简单,但是其最致命的一个缺点就是图像收敛速度很慢..原因在于从摄影机发射出的每一条光线若不 ...

  10. HTMLCollection 对象详解,以及为什么循环获取的dom合集操作可能会出现下标不正确的情况?

    有时候循环dom合集,然后操作其中的某些dom之后,发现下标不正确了 比如我们要删除一个dom合集的时候: var selectDom = document.getElementsByClassNam ...