-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path306.Additive-Number.py
47 lines (37 loc) · 1.21 KB
/
306.Additive-Number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# https://leetcode.com/problems/additive-number/
#
# algorithms
# Medium (28.44%)
# Total Accepted: 41,434
# Total Submissions: 145,714
# beats 100.0% of python submissions
class Solution(object):
def isAdditiveNumber(self, num):
"""
:type num: str
:rtype: bool
"""
length = len(num)
if length < 3:
return False
def recursive(st, nd, idx):
if idx == length:
return True
if st == '':
if num[idx] == '0':
return recursive('0', '', idx + 1)
for i in xrange(1, length / 2 + 1):
if recursive(num[:i], '', i):
return True
elif nd == '':
if num[idx] == '0':
return recursive(st, '0', idx + 1)
for i in xrange(idx + 1, length):
if recursive(st, num[idx:i], i):
return True
else:
target = str(int(st) + int(nd))
if num.startswith(target, idx):
return recursive(nd, target, idx + len(target))
return False
return recursive('', '', 0)