Leetcode 306. Additive Number

來源:互聯網
上載者:User

標籤:檢查   leading   als   遞推   log   term   沒有   bool   form   

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.

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 containing only digits ‘0‘-‘9‘, write a function to determine if it‘s an additive number.

我一開始想到了用DP。但是無法寫出遞推函數。其實本題用類似brute force的搜尋可以通過OJ。本題學習了兩個Python內嵌的函數,一個是itertools.combination(list, num)。可以列出list中取num個數位所有combination而且沒有重複。

另外一個是 string1.startswith(string2, beg, end)。這個函數可以檢查string1的從beg開始長度為end的sub string是不是以string2開頭。

 1     def isAdditiveNumber(self, num): 2         """ 3         :type num: str 4         :rtype: bool 5         """ 6         n = len(num) 7         for i, j in itertools.combinations(range(1, n), 2): 8             a, b = num[:i], num[i:j] 9             if a != str(int(a)) or b != str(int(b)):10                 continue11             while j < n:12                 c = str(int(a)+int(b))13                 if num.startswith(c, j):14                     j += len(c)15                     a, b = b, c16                 else:17                     break18             if j == n:19                 return True20         return False

本題還可以用遞迴的解法

Leetcode 306. Additive Number

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.