LeetCode *** 306. Additive Number

来源:互联网 发布:那种牌子的网络电视好 编辑:程序博客网 时间:2024/05/16 04:56

题目:

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 sequence1, 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?


分析:

回溯。


代码:

class Solution {public:    bool isAdditiveNumber(string num) {        int len=num.length();        for(int i=1;i<=len/2;++i)            for(int j=1;j<=(len-i)/2;++j){                if(check(num.substr(0,i),num.substr(i,j),num.substr(i+j)))                    return true;            }        return false;    }        bool check(string add,string added,string result){        if(result=="")return true;        if(added.length()>1&&added[0]=='0')return false;        string res="";        int lena=add.length()-1,lenad=added.length()-1;        int flag=0,t;        while(lena>=0||lenad>=0){            t=0;            if(lena>=0){                t+=add[lena]-'0';                --lena;            }            if(lenad>=0){                t+=added[lenad]-'0';                --lenad;            }            t+=flag;            flag=t/10;            t=t%10;            res.insert(res.begin(),t+'0');        }        if(flag)res.insert(res.begin(),flag+'0');        if(res.length()>result.length())return false;        int len=res.length(),pos=0;        while(pos<len){            if(res[pos]!=result[pos])return false;            pos++;        }        return check(added,result.substr(0,len),result.substr(len));    }};

0 0
原创粉丝点击