1 class Solution:
 2     def backTrack(self,num,l,idx,n):
 3         if idx >= n:
 4             if len(l) >= 3:
 5                 return True
 6             else:
 7                 return False
 8         for i in range(idx,n):
 9             s = num[idx:i+1]
10             leng = len(s)
11             cur = int(s)
12             s_cur = str(cur)
13             if s_cur != s:
14                 continue#有前导0
15             if len(l) < 2:
16                 l.append(cur)
17                 res = self.backTrack(num,l,idx+leng,n)
18                 if res:
19                     return True
20                 else:
21                     if len(l) != 0:
22                         l.pop(-1)
23             else:
24                 pre = l[-1]
25                 prepre = l[-2]
26                 if pre + prepre == cur:
27                     l.append(cur)
28                     res = self.backTrack(num,l,idx+leng,n)
29                     if res:
30                         return True
31                     else:
32                         if len(l) != 0:
33                             l.pop(-1)
34         return False
35 
36 
37     def isAdditiveNumber(self, num: str) -> bool:
38         n = len(num)
39         return self.backTrack(num,[],0,n)

算法思路:回溯法。

posted on 2020-04-07 21:49  Sempron2800+  阅读(174)  评论(0编辑  收藏  举报