题目:

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. 分布式缓存技术redis学习—— 深入理解Spring Redis的使用

    关于spring redis框架的使用,网上的例子很多很多.但是在自己最近一段时间的使用中,发现这些教程都是入门教程,包括很多的使用方法,与spring redis丰富的api大相径庭,真是浪费了这么 ...

  2. CentOS 7.2下安装Mono 5.0

    微软Build2017大会期间.NET领域的.NET core之外,就是Visual Studio For Mac,大家都知道Visual Studio For Mac 是基于Mono运行的,Mono ...

  3. vue的双向绑定原理及实现

    前言 使用vue也好有一段时间了,虽然对其双向绑定原理也有了解个大概,但也没好好探究下其原理实现,所以这次特意花了几晚时间查阅资料和阅读相关源码,自己也实现一个简单版vue的双向绑定版本,先上个成果图 ...

  4. 《Android进阶》之第六篇 Fragment 的使用2

    最近通过学习,对fragment的使用有了新的认识. 一开始接触android的时候,很是受不了这个fragment,总感觉它把一个简单的事情搞复杂啦,所以每次新建工程的时候总是固执的选择empty ...

  5. 六、 从Controller中访问模板数据(ASP.NET MVC5 系列)

    在这一章节中,我们将创建一个新的MoviesController类,写代码获取movie数据并用视图模板将它们显示到浏览器中. 在我们进行下一操作之前先Build the application.如果 ...

  6. Oracle listener服务启动后又停止的解决方案

    这是Oracle监听服务.忘了说我的版本是Oracle10g. 我装完Oracle数据库之后,然后用第三方工具plsql去连接,提示no listener,首先我反复检查tnsnames.ora配置文 ...

  7. Windows、Office系列产品精华部分集锦

    提示 有了这个帖子麻麻再也不用担心我因为四处找Microsoft家的软件和系统而四处劳累所烦恼了! 首先,你们最爱的老XP同志,XP同志虽然退休了,但是依然坚持在岗位上,向他致敬!! Windows ...

  8. VR全景智慧城市-提前进入商家观景,涵盖实体行业

    互联网发展的迅猛势头,让很多的实体商家翻了个大跟头,更有言说,未来的大街小巷根本见不到逛街的人,可是线上商城相继曝出的假货谁来买单?相比之下眼见为实更让消费者心里觉得踏实.所以,全景智慧城市更能满足大 ...

  9. golang实现dns域名解析(三):响应报文分析

    前面说了构造请求发送报文,接下来我们好好研究下如何解析服务器端发回来的应答信息. 首先还是用前面的程序代码发一个请求,用抓包工具看看应答的内容有哪些: 截图的第一部分是返回信息的统计,表明这个返回的包 ...

  10. cursor 属性

    鼠标 样式 default 默认光标(通常是一个箭头) auto 默认.浏览器设置的光标. crosshair 光标呈现为十字线. pointer 光标呈现为指示链接的指针(一只手) move 此光标 ...