1. Additive Number

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

Constraints:

  • num consists only of digits '0'-'9'.
  • 1 <= num.length <= 35

Follow up:

How would you handle overflow for very large input integers?

  • 回溯法。注意回溯中,在进入分支之后,还要退出分支
  • 大数运算。用字符串实现大数的加减乘除
// 大数,只需要重载加法
class BigNum{
public:
string val;
BigNum(string s, bool hasreversed = false){
if(!hasreversed){
reverse(s.begin(), s.end());
}
val = s;
}
void Print(){
for(int i = val.size()-1; i>=0; --i)cout << val[i];
cout << endl;
}
//先加两个字符串公有的部分,再加上剩下的部分
//如果进位不为0,还要加上进位
BigNum operator + (BigNum &b){
string s1 = b.val, res;
int carry = 0, i = 0;
while(i < s1.size() && i < val.size()){
int tmp = carry + (s1[i]-'0') + (val[i]-'0');
carry = tmp / 10;
res += tmp % 10 + '0';
i++;
}
while(i < s1.size()){
int tmp = carry + (s1[i]-'0');
carry = tmp / 10;
res += tmp % 10 + '0';
i++;
}
while(i < val.size()){
int tmp = carry + (val[i]-'0');
carry = tmp / 10;
res += tmp % 10 + '0';
i++;
}
if(carry)res += carry + '0';
return BigNum(res, true);
}
}; class Solution {
public:
bool isAdditiveNumber(string num) {
vector<BigNum>path;
return dfs(num, 0, path);
}
bool dfs(string &num, int pos, vector<BigNum>&path){
//结束条件,当pos到达了字符串末尾,则枚举完毕,看path的长度,如果大于2,说明前面的枚举是成功的
if(pos >= num.size())return path.size() >= 3;
int len = path.size();
// 如果len<2,说明最前面的两个数字还没有选出来,枚举选择即可
// 不能出现前缀0,即02 00这些是不合法的,只能选成0
if(len < 2){
for(int i = 1; i <= num.size(); ++i){
if(num[0] == '0' && i > 1)break;
path.push_back(BigNum(num.substr(0, i)));
for(int j = i+1; j <= num.size(); ++j){
if(num[i] == '0' && j > i + 1)break;
path.push_back(BigNum(num.substr(i, j-i)));
if(dfs(num, j, path)){
return true;
}else{
path.pop_back();
}
}
path.pop_back();
}
}else{
// 算出前两个数字的和,看对应的字符串是不是num的子串,不是的话返回,是的话往后搜索
BigNum next_int = path[len-2] + path[len-1];
string next_str = next_int.val;
reverse(next_str.begin(), next_str.end());
if(num.substr(pos, next_str.size()) == next_str){
path.push_back(next_int);
bool res = dfs(num, pos + next_str.size(), path);
path.pop_back();
return res;
}else{
return false;
}
}
return false;
}
};

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

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

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

  2. Leetcode 306. Additive Number

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

  3. 【刷题-LeetCode】200 Number of Islands

    Number of Islands Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. ...

  4. 【刷题-LeetCode】191 Number of 1 Bits

    Number of 1 Bits Write a function that takes an unsigned integer and return the number of '1' bits i ...

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

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

  6. 【LeetCode】306. Additive Number

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

  7. 306. Additive Number

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

  8. 306 Additive Number 加法数

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

  9. LeetCode刷题------------------------------LeetCode使用介绍

    临近毕业了,对技术有种热爱的我也快步入码农行业了,以前虽然在学校的ACM学习过一些算法,什么大数的阶乘,dp,背包等,但是现在早就忘在脑袋后了,哈哈,原谅我是一枚菜鸡,为了锻炼编程能力还是去刷刷Lee ...

随机推荐

  1. CF200B Drinks 题解

    Content 有 \(n\) 杯饮料,第 \(i\) 杯饮料中橙汁占 \(a_i\%\).现在请求出这 \(n\) 杯饮料混合成一杯饮料后的橙汁所占百分比. 数据范围:\(1\leqslant n\ ...

  2. CF1569A Balanced Substring 题解

    Content 给定一个长度为 \(n\) 且仅包含字符 a.b 的字符串 \(s\).请找出任意一个使得 a.b 数量相等的 \(s\) 的子串并输出其起始位置和终止位置.如果不存在请输出 -1 - ...

  3. 前端实现list排序

    需求 针对list中某个字段,实现list的升序和降序 效果图 代码 我是用在angular1.X中项目的,根据list中的sort字段进行排序. # sort.html <style> ...

  4. docker启动WARNING:IPv4 forwarding is disabled. Networking will not work.

    docker启动容器报错IPv4 forwarding is disabled. Networking will not work. [root@localhost ~]# docker run -p ...

  5. thymeleaf标签在js中调用转义变量与不转义变量写法

    转义写法 [[${content.title}]] 不转义写法 有时候我们可能需要在页面上显示html代码 这样的话 就不能把字符串转义了 这时候可以采用下面这种写法 [(${content.txt} ...

  6. 金智维RPA培训(一)产品基础架构-RPA学习天地

    1.产品组成分为:Server,control,agent三个组件,支持CS和BS架构.独有的中继服务器可以解决跨网段的问题,这里应该还是采用了多网卡模式. 其中:Agent负责对流程的执行工作.Co ...

  7. nim_duilib(4)之CheckBox

    introduction 更多控件用法,请参考 here 和 源码. 本文的代码基于这里 xml文件添加代码 基于上一篇, 继续向basic.xml中添加下面关于CheckBox的代码. xml完整源 ...

  8. 【LeetCode】847. Shortest Path Visiting All Nodes 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/shortest ...

  9. 【LeetCode】851. Loud and Rich 解题报告(Python)

    [LeetCode]851. Loud and Rich 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http:// ...

  10. 常见分布式唯一ID生成策略

    方法一: 用数据库的 auto_increment 来生成 优点: 此方法使用数据库原有的功能,所以相对简单 能够保证唯一性 能够保证递增性 id 之间的步长是固定且可自定义的 缺点: 可用性难以保证 ...