Problem
You are given two integers, m
and k
, and an integer array nums
.
A sequence of integers seq
is called magical if:
seq
has a size ofm
.0 <= seq[i] < nums.length
- The binary representation of
2seq[0] + 2seq[1] + ... + 2seq[m - 1]
hask
set bits.
The array product of this sequence is defined as prod(seq) = (nums[seq[0]] * nums[seq[1]] * ... * nums[seq[m - 1]])
.
Return the sum of the array products for all valid magical sequences.
Since the answer may be large, return it modulo 10^9 + 7
.
A set bit refers to a bit in the binary representation of a number that has a value of 1.
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= k <= m <= 30
1 <= nums.length <= 50
1 <= nums[i] <= 10^8
Examples
Solution
Method 1 – Bitmask Enumeration and Combinatorics
Intuition
We need to count all sequences of length m (with possible repeated indices) such that the sum of 2^seq[i] for i in 0..m-1 has exactly k set bits. For each such sequence, we multiply the corresponding nums values and sum the products. Since m and nums.length are small, we can enumerate all possible multisets using combinatorics and bitmasking.
Approach
- For each possible multiset of indices (with repetition) of length m, count the number of ways to arrange them (multinomial coefficient).
- For each multiset, compute the sum of 2^i * count[i] for all i.
- If the number of set bits in this sum is k, compute the product of nums[i]^count[i] for all i.
- Multiply the product by the multinomial coefficient and add to the answer.
- Use recursion with memoization to efficiently enumerate all multisets.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^m)
, since we enumerate all multisets of length m from n elements (with repetition), but for small m and n this is feasible. - 🧺 Space complexity:
O(m + n)
, for recursion stack and counters.