码迷,mamicode.com
首页 > 其他好文 > 详细

306. Additive Number

时间:2019-02-09 01:06:24      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:bsp   highlight   must   class   input   first   long   isa   seq   

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, 190.
             1 + 99 = 100, 99 + 100 = 199

 

Approach #1: 

class Solution {
public:
    bool isAdditiveNumber(string num) {
        if (num.length() < 3) return false;
        // if (num == "000") return true;
        // cout <<"num.length() = " << num.length() << endl;
        for (int i = 1; i <= num.length() / 2; ++i) {    // the first number‘s length;
            if (num[0] == ‘0‘ && i > 1) return false;
            string s_first = num.substr(0, i);
            long first = stol(s_first);
            // cout << "first = " << s_first << endl;
            for (int j = 1; num.length()-i-j >= max(i, j); ++j) {
                string s_second = num.substr(i, j);
                if (j > 1 && s_second[0] == ‘0‘) break;
                long second = stol(s_second);
                // cout << "second = " << s_second << endl;
                if (isValid(first, second, i+j, num)) {
                    return true;
                }
            }
        }
        return false;
    }
    
private:
    bool isValid(long first, long second, int start, string num) {
        // cout << "start = " << start << endl;
        // cout << first << ‘ ‘ << second << endl;
        if (start == num.length()) return true;
        second = second + first;
        first = second - first;
        // cout << first << ‘ ‘ << second << endl;
        string sum = to_string(second);
        // cout << "sum = " << sum << endl;
        return C_startWith(sum, start, num) && isValid(first, second, start+sum.length(), num);
    }
    
    bool C_startWith(string sum, int start, string num) {
        int len = sum.length();
        string temp = num.substr(start, len);
        return temp == sum;
    }
};

  

 

306. Additive Number

标签:bsp   highlight   must   class   input   first   long   isa   seq   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/10357028.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!