306-累加数

累加数是一个字符串,组成它的数字可以形成累加序列。

一个有效的累加序列必须至少包含 3 个数。除了最开始的两个数以外,字符串中的其他数都等于它之前两个数相加的和。

给定一个只包含数字 ‘0’-‘9’ 的字符串,编写一个算法来判断给定输入是否是累加数。

说明: 累加序列里的数不会以 0 开头,所以不会出现 1, 2, 03 或者 1, 02, 3 的情况。

示例 1:

输入: “112358”
输出: true
解释: 累加序列为: 1, 1, 2, 3, 5, 8 。1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
示例 2:

输入: “199100199”
输出: true
解释: 累加序列为: 1, 99, 100, 199。1 + 99 = 100, 99 + 100 = 199

思路:这题枚举就可以,我们首先要枚举出前面两个数,然后递推验证即可,其中涉及到模拟大数加法,个人感觉不用写成递归回溯的形式,两层循环便可以。

class Solution {
public:

    int temp[40];
    string Add(string& a,string& b,int len1,int len2)
    {
        int cnt=0;
        int c=0;
        while(cnt<=len1&&cnt<=len2)
        {
            temp[cnt]=(a[len1-cnt]-'0')+(b[len2-cnt]-'0')+c;
            c=temp[cnt]/10;
            temp[cnt]%=10;
            ++cnt;
        }
        while(cnt<=len1)
        {
            temp[cnt]=(a[len1-cnt]-'0')+c;
            c=temp[cnt]/10;
            temp[cnt]%=10;
            ++cnt;
        }
        while(cnt<=len2)
        {
            temp[cnt]=(b[len2-cnt]-'0')+c;
            c=temp[cnt]/10;
            temp[cnt]%=10;
            ++cnt;
        }
        if(c) temp[cnt]=c;
        else --cnt;
        string str="";
        for(int i=0;i<=cnt;++i)
        {
            char h='0'+temp[i];
            str=h+str;
        }
        return str;
    }
    bool Judge(string& num,string& c,int n,int l)
    {
        int k=c.size();
        for(int i=0;i<k;++i)
        {
            if(i+l>=n) return false;
            if(num[i+l]!=c[i]) return false;
        }
        return true;
    }
    bool isAdditiveNumber(string num) {
        int len=num.size();
        if(len<3) return false;
        for(int i=1;i<len-1;++i)
        {
            for(int j=1;j<len-1;++j)
            {
                if(i+j>=len) continue;
                string a=num.substr(0,i);
                string b=num.substr(i,j);
                int k1=a.size();
                int k2=b.size();
                if((a[0]=='0'&&k1!=1)||(b[0]=='0'&&k2!=1)) continue;
                string c=Add(a,b,i-1,j-1);
                if(Judge(num,c,len,i+j))
                {
                    int h=i+j+c.size();
                    if(h==len) return true;
                    while(h<len)
                    {
                        a=b;
                        b=c;
                        c=Add(a,b,a.size()-1,b.size()-1);
                        if(!Judge(num,c,len,h))
                        {
                            break;
                        }
                        h+=c.size();
                        if(h==len) return true;
                    }
                }
            }
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值