zoukankan      html  css  js  c++  java
  • leetcode1395

     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

  • 相关阅读:
    H3C-路由器密码恢复
    H3C-交换机密码恢复
    H3C-端口镜像
    [洛谷P4234]最小差值生成树
    [BZOJ4003]城池攻占
    [BZOJ1058]报表统计
    [BZOJ1584]Cleaning Up 打扫卫生
    [BZOJ3733]Iloczyn
    [HDU5709]Claris Loves Painting
    [BZOJ5109]大吉大利,晚上吃鸡!
  • 原文地址:https://www.cnblogs.com/asenyang/p/12591685.html
Copyright © 2011-2022 走看看