[LeetCode]Additive Number

题目链接:Additive Number
题目内容:

Additive number is a positive integer 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 represents an integer, write a function to determine if it’s an additive number.

Follow up:
How would you handle overflow for very large input integers?

题目解法

这是一道典型的枚举问题,可以用回溯法解决。
回溯的策略为,在开始时从长度为1的字串开始枚举,设这个值为s1,然后从剩下的部分中继续从长度为1开始枚举,设这个值为s2,此时余下的部分为s3,如果s1+s2(代数和)所对应的字符串在s3中能找到,并且这个字串在s3的开头,则说明找到了符合条件的部分序列,接着让s2=s1,重复这个过程。终止条件为在s3中拿掉s1+s2所对应的字符串后长度为0。
我们的递归函数参数如下:

void DFS(int len,string num,string s1);

len代表的是从头开始查找时,对s1长度的枚举。在后序的查找中,由于s1取自上次的s2,因此len不在对s1起作用,但是注意到len会影响是否在剩余串中去掉s1,因此再后序递归中len必须传入0。为了区分从头开始的查找与中间的查找,我们在第一次进入DFS时s1传入"",因为中间查找时s1传入的值为刚找到的s2,因此不会为""

代码如下:

class Solution {
private:
    bool m_res;
public:
    long long str2num(string str){
        stringstream ss(str);
        long long n;
        ss >> n;
        return n;
    }
    string num2str(long long num){
        stringstream ss;
        ss << num;
        return ss.str();
    }
    void DFS(int len,string num,string s1){
        if(s1 == "") s1 = num.substr(0,len);
        if(s1.length() > 1 && s1[0] == '0') return;
        string left = num.substr(len);
        int leftLen = left.length();
        for(int i = 1; i < leftLen; i++){
            string s2 = left.substr(0,i);
            if(s2.length() > 1 && s2[0] =='0') return;
            string sum = num2str(str2num(s1) + str2num(s2));
            string subleft = left.substr(i);
            int subpos = subleft.find(sum);
            if(subpos == 0){
                string finalLeft = subleft.substr(sum.length());
                int subLen = finalLeft.length();
                if(subLen == 0){
                   m_res = true;
                   return;
                }
                DFS(0,subleft,s2);
            }
        }
    }
    bool isAdditiveNumber(string num) {
        vector<string> res;
        int len = num.length();
        m_res = false;
        for(int i = 1; i < len - 1;i++){
            DFS(i,num,"");
            if(m_res) return true;
        }
        return false;
    }
};

posted on 2015-11-23 14:34  张大大123  阅读(137)  评论(0编辑  收藏  举报

导航