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 对于任一种情况,只要定下来前两个数字,后边就都是确定的了,所以只需要遍历前两个数字的所有情况。

  • 相关阅读:
    php中&符号什么意思
    lucene 笔记
    yslow详细解释
    sqlserver中如何实现时间按月,日,小时分组查询
    用Lucene.net对数据库建立索引及搜索2
    lucene.net索引文件存储简析
    C #中的几个线程同步对象方法 1
    lucene 全文检索简介
    判断jquery对象是否可见
    Lucene.net多字段(Fields)、多索引目录(IndexSearcher)搜索
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9772276.html
Copyright © 2011-2022 走看看