306. Additive Number

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

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

class Solution {
    public boolean isAdditiveNumber(String num) {
        int k = num.length();
        if(k < 3) return false;
        for(int i = 1; i <= num.length() / 2; i++){
            //选第一个数字A,长度从1到最大长度的一半(11011,A=11)
            if(num.charAt(0) == '0' && i >= 2) return false;//如果第一个字符是0,而且A大于1位数就返回false
            Long a = Long.valueOf(num.substring(0, i));
            for(int j = 1; k - i - j >= Math.max(i, j); j++){
                if(num.charAt(i) == '0' && j > 1) break;
                Long b = Long.valueOf(num.substring(i, i+j));
                if(helper(a, b, i+j, num)) return true;
        }
        }
                return false;
    }
     public boolean helper(Long a, Long b, int begin, String num){
        if(begin == num.length()) return true;
        b = a + b;
        a = b - a;
        String res = b.toString();
        return num.startsWith(res, begin) && helper(a, b, begin + res.length(), num);
    }
}

https://leetcode.com/problems/additive-number/discuss/75572/*Java*-very-straightforward-solution-with-detailed-explanation

https://www.youtube.com/watch?v=LziJZT2uRwc

不错,细节挺多的

posted @ 2019-09-19 13:13  Schwifty  阅读(165)  评论(0编辑  收藏  举报