LC.982. Triples with Bitwise AND Equal To Zero

LC.982. Triples with Bitwise AND Equal To Zero_第1张图片
LC.982. Triples with Bitwise AND Equal To Zero_第2张图片

class Solution(object):
    def countTriplets(self, A):
        """
        这道题就是一个带记忆的暴力搜
        """
        from collections import defaultdict
        result = 0
        # 存key- count ,表示A中能与key & 结果为0的元素的个数
        memo =  defaultdict(lambda : -1)
        for i in range(len(A)):
            for j in range(len(A)):
                #保存中间结果,避免重复计算
                first_two_and = A[i] & A[j]
                if memo[first_two_and] == -1:
                    count = 0
                    for k in range(len(A)):
                        if first_two_and  & A[k] == 0:
                            count += 1
                    memo[first_two_and] = count
                result += memo[first_two_and]
        return result

你可能感兴趣的:(LeetCode)