题目:

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. Maven学习-Profile详解

    Profile能让你为一个特殊的环境自定义一个特殊的构建:profile使得不同环境间构建的可移植性成为可能.Maven中的profile是一组可选的配置,可以用来设置或者覆盖配置默认值.有了prof ...

  2. memcache 启动 failed to start

    以为是 端口冲突,到注册表中直接改了memcache的注册表,还是启动不了.memcache运行不了,还能咋办,看防火墙有没有阻止程序运行呗 勾上,我的windows 上的memcache 就可以运行 ...

  3. xpo-4大类

      Xpo (XPBaseObject.XPLiteObject.XPCustomObject.XPObject) 类名 延后删除 是否乐观锁定 提供OID字段 XPBaseObject 不支持 支持 ...

  4. maven 热部署至tomcat

    1.配置tomcat的界面访问账号和权限./tomcat/conf目录下tomcat-users.xml添加 这里是根据自己的需求添加的一个角色权限 <role rolename="a ...

  5. java关键字transient与volatile小结

    本文转自:http://heaven-arch.iteye.com/blog/1160693 transient和volatile两个关键字一个用于对象序列化,一个用于线程同步,都是Java中比较高阶 ...

  6. How to get the file in a resource folder

    In a Maven project, we may often struggle to get a certain file (e.g. json file or sql file). Here i ...

  7. 开涛spring3(7.4) - 对JDBC的支持 之 7.4 Spring提供的其它帮助

    7.4  Spring提供的其它帮助 7.4.1  SimpleJdbc方式 Spring JDBC抽象框架提供SimpleJdbcInsert和SimpleJdbcCall类,这两个类通过利用JDB ...

  8. java虚拟机学习-JVM调优总结-分代垃圾回收详述(9)

    为什么要分代 分代的垃圾回收策略,是基于这样一个事实:不同的对象的生命周期是不一样的.因此,不同生命周期的对象可以采取不同的收集方式,以便提高回收效率. 在Java程序运行的过程中,会产生大量的对象, ...

  9. 如何通过 WebP 兼容减少图片资源大小

    作者:学军又拍云 CDN 服务公测 WebP 自适应功能,为客户减少图片资源大小.本文我们将一起来阐述WebP兼容的来龙去脉. 前言我们知道,理想的网页应该在 1 秒内打开,而在页面的整体大小中,图片 ...

  10. Akka(4): Routers - 智能任务分配

    Actor模式最大的优点就是每个Actor都是一个独立的任务运算器.这种模式让我们很方便地把一项大型的任务分割成若干细小任务然后分配给不同的Actor去完成.优点是在设计时可以专注实现每个Actor的 ...