1 class Solution:
 2     def __init__(self):
 3         #self.l = []
 4         self.count = 0
 5 
 6     def backTrack(self,rating,temp,idx,inc):
 7         if inc == 0:#递减
 8             if len(temp) == 3:
 9                 #self.l.append(temp[:])
10                 self.count += 1
11                 return
12             else:
13                 for i in range(idx,len(rating)):
14                     if len(temp) == 0 or rating[i] < temp[-1]:
15                         temp.append(rating[i])
16                     else:
17                         continue
18                     self.backTrack(rating,temp,i+1,inc)
19                     if len(temp) > 0:
20                         temp.pop(-1)
21         else:#递增
22             if len(temp) == 3:
23                 #self.l.append(temp[:])
24                 self.count += 1
25                 return
26             else:
27                 for i in range(idx,len(rating)):
28                     if len(temp) == 0 or rating[i] > temp[-1]:
29                         temp.append(rating[i])
30                     else:
31                         continue
32                     self.backTrack(rating,temp,i+1,inc)
33                     if len(temp) > 0:
34                         temp.pop(-1)
35 
36 
37     def numTeams(self, rating: 'List[int]') -> int:
38         self.backTrack(rating,[],0,0)
39         self.backTrack(rating,[],0,1)
40         #print(self.l)
41         return self.count

算法思路:回溯法。

对数组进行两次回溯,一次寻找递减的三元组;另一次寻找递增的三元组。

使用递归进行查询,到找到3个元素的符合条件的,就记录+1

posted on 2020-03-29 12:38  Sempron2800+  阅读(187)  评论(0编辑  收藏  举报