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
Algorithm thinking: backtracking.
The array back twice, once to find triples decreasing; look for another increment of triples.
Recursive query, to find qualified three elements, it is recorded +1