<p>Given an integer array nums, return <em>the number of <strong>AND triples</strong></em>.</p>

<p>An <strong>AND triple</strong> is a triple of indices <code>(i, j, k)</code> such that:</p>

<ul>
	<li><code>0 &lt;= i &lt; nums.length</code></li>
	<li><code>0 &lt;= j &lt; nums.length</code></li>
	<li><code>0 &lt;= k &lt; nums.length</code></li>
	<li><code>nums[i] &amp; nums[j] &amp; nums[k] == 0</code>, where <code>&amp;</code> represents the bitwise-AND operator.</li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [2,1,3]
<strong>Output:</strong> 12
<strong>Explanation:</strong> We could choose the following i, j, k triples:
(i=0, j=0, k=1) : 2 &amp; 2 &amp; 1
(i=0, j=1, k=0) : 2 &amp; 1 &amp; 2
(i=0, j=1, k=1) : 2 &amp; 1 &amp; 1
(i=0, j=1, k=2) : 2 &amp; 1 &amp; 3
(i=0, j=2, k=1) : 2 &amp; 3 &amp; 1
(i=1, j=0, k=0) : 1 &amp; 2 &amp; 2
(i=1, j=0, k=1) : 1 &amp; 2 &amp; 1
(i=1, j=0, k=2) : 1 &amp; 2 &amp; 3
(i=1, j=1, k=0) : 1 &amp; 1 &amp; 2
(i=1, j=2, k=0) : 1 &amp; 3 &amp; 2
(i=2, j=0, k=1) : 3 &amp; 2 &amp; 1
(i=2, j=1, k=0) : 3 &amp; 1 &amp; 2
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [0,0,0]
<strong>Output:</strong> 27
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
	<li><code>0 &lt;= nums[i] &lt; 2<sup>16</sup></code></li>
</ul>

'''
Diff permutation of indices are counted as different good tuples.

Intuition: Trying all pairs of points does not create too many results.
Create all pairwise AND as A. Note that A has max size of 2^16. This is much less than n^2.
Which is why we can do another loop of O(A * n). :D
'''

# class Solution:
#     def countTriplets(self, nums: List[int]) -> int:
#         # Find all pairs and their freq
#         pairs = defaultdict(int)
#         n=len(nums)
#         for i in range(n):
#             for j in range(n):
#                 v = nums[i] & nums[j]
#                 pairs[v] += 1
#         ans=0
#         for v, cnt in pairs.items():
#             for i, c in enumerate(nums):
#                 if v & c == 0:
#                     ans += cnt
#         return ans

'''
second soln is DP
dp[k][x] = num ways to use k elements, AND them to form x.
'''

class Solution:
    def countTriplets(self, nums: List[int]) -> int:
        maxn = max(nums)
        dp = [[0] * (maxn+1) for _ in range(3)]
        
        for x in nums:
            dp[0][x] += 1
        for k in range(0,2):
            for mask in range(maxn+1):
                if dp[k][mask]:
                    for x in nums:
                        dp[k+1][mask & x] += dp[k][mask]
        return dp[2][0]
18400