一、问题描述
给定一个数组。三个索引
- i,i ~ [0, array.length)
- j, j ~ [0, array.length)
- k, k ~ [0, array.length)
求有多少种组合方式使得 array[i] & array[j] & array[k] = 0?
二、思路
用缓存存储遍历过的结果
三、Code
1 package algorithm; 2 3 import java.util.Arrays; 4 5 /** 6 * Created by adrian.wu on 2019/2/27. 7 */ 8 public class CountTriplets { 9 public int countTriplets(int[] A) { 10 int n = A.length, res = 0; 11 int[] vd = new int[(1 << 16)]; 12 Arrays.fill(vd, -1); 13 for (int i = 0; i < n; i++) { 14 for (int j = 0; j < n; j++) { 15 int ijAnd = A[i] & A[j]; 16 if (vd[ijAnd] == -1) { 17 vd[ijAnd] = 0; 18 for (int k = 0; k < n; k++) { 19 if ((ijAnd & A[k]) == 0) vd[ijAnd]++; 20 } 21 } 22 res += vd[ijAnd]; 23 } 24 } 25 return res; 26 } 27 }