zoukankan      html  css  js  c++  java
  • 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:
        def isAdditiveNumber(self, num):
            """
            :type num: str
            :rtype: bool
            """
            if len(num)<=2:
                return False
            def judge(s): #judge a string valid or not
                if len(s)==1:
                    return True
                if len(s)==0:
                    return False
                if s[0]=='0':
                    return False
                return True
            def solve(i,j): #judge this divided method vaild or not
                a,b = num[:i],num[i:j]
                if judge(a) is False or judge(b) is False:
                    return False
                n1,n2 = int(a),int(b)
                # print(n1,n2)
                while True:
                    n3 = n1 + n2
                    c = str(n3)
                    if j+len(c)>len(num) or n3!=int(num[j:j+len(c)]):
                        return False
                    if j+len(c)==len(num):
                        return True
                    n1 = n2
                    n2 = n3
                    j = j+len(c)
                    # print('n2:',n2,'n1:',n1,'j:',j)
            for i in range(1,len(num)//2+1):
                for j in range(i+1,len(num)):
                    # print(i,j)
                    if solve(i,j):
                        return True
            return False
    

    手动dfs 对于任一种情况,只要定下来前两个数字,后边就都是确定的了,所以只需要遍历前两个数字的所有情况。

  • 相关阅读:
    15 | 二分查找(上):如何用最省内存的方式实现快速查找功能?
    11 | 线程:如何让复杂的项目并行执行?
    数据结构与算法-10-递归调用
    (图文并茂,权威最详细)Wireshark抓包分析 TCP三次握手/四次挥手详解
    总结-自己傻的坑学习java spingboot不仔细
    网络抓包
    数据库简介
    JavaSE基础之Map与Collection
    JavaSE基础之抽象类与接口
    JavaSE基础之重载和重写
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9772276.html
Copyright © 2011-2022 走看看