306. Additive Number 给定字符串分割进行类似斐波那契数列

113 篇文章 0 订阅

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.


1.我的解法 哈哈哈,开心,我竟然做出来了,,,真的不知所以然的AC了。。。 不过过程也是调整了很多次

就是递归,每次都进行前两个数字的分割,然后计算第三个数是否相等。若第三个数分割后刚好分割完了,说明整个字符串分割完了,就是对的,返回正确;否则不断循环;当某次加和成功,就递归下一次,用begin记录下一次的开始位置。

开始是直接两次循环,没有套递归,导致出现以下案例:

12122436

则开始时会分割成 1+21 =22,但是这样分割不对,不对时需要重头分割;因此需要加递归。

class Solution {
public:
    int get_size(int nums){
        int count = 0;
        while(nums){
            nums = nums / 10;
            count++;
        }
        return count;
    }
    
    bool isadditive(string num, int begin){
    for(int i = begin; i < num.size()-2; i++){
        string s1;
        for(int j = i+1; j < num.size(); j++){
            s1 = num.substr(begin,i+1-begin);
            string s2 = num.substr(i+1,j-i);
            int i1 = atoi(s1.c_str());
            int i2 = atoi(s2.c_str());
            int res = i1 + i2;
            int pos = get_size(res);
            string s3 = num.substr(j+1, pos);
            int i3 = atoi(s3.c_str());
            if(res == i3){
                if(j+pos+1 == num.size()) return true;
                bool res = isadditive(num, i+1);
                if(res) return true;
                break;
                }
            if(s2 == "0") break;
            }
            if(s1=="0") return false;
        }
    return false;
    }
    bool isAdditiveNumber(string num) {
        if(num.size() < 3) return false;
        return isadditive(num,0);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值