Problem Description
Given an integer array nums and a positive integer k, the power of an array is defined as the number of its subsequences (not necessarily contiguous) that sum exactly to k. The task is to calculate the sum of the power over all subsequences of nums. Since the answer can be very large, return it modulo 10^9 + 7.
Key Insights
- Notice that each subsequence X of nums contributes the count of its own sub-subsequences Y with sum(Y) == k.
- Reorder the summation. Instead of iterating over every subsequence X and then counting valid Y ⊆ X, we can first choose Y ⊆ nums with sum k and then count in how many supersets X (of nums) the chosen Y appears.
- For a fixed valid subset Y with sum k and |Y| = t, any subsequence X that contains Y is obtained by choosing an arbitrary subset from the remaining (n – t) elements. There are 2^(n – t) such choices.
- Hence the answer becomes the sum over all subsets Y ⊆ nums such that sum(Y)==k of 2^(n – |Y|).
- Use dynamic programming to count, for each possible subset Y (by tracking current sum and the number t of elements chosen), the number of ways to achieve each sum.
- Finally, multiply each count with the corresponding power weight 2^(n-t) and take the result modulo 10^9+7.
Space and Time Complexity
Time Complexity: O(n * k * n) = O(n^2 * k) since we iterate over each element and update DP for sums up to k and count up to n. Space Complexity: O(k * n) for the DP table.
Solution
We reformulate the double counting as follows. Instead of summing the power for every subsequence X, we reverse the order and sum over every possible subsequence Y of nums which has sum exactly k. For each such Y (with |Y| = t), its contribution is 2^(n – t) because any superset X (with Y ⊆ X ⊆ nums) will “inherit” the subsequence Y.
We perform a DP where dp[s][t] counts the number of ways to pick t elements (from some prefix of nums) that sum to s. Initialize dp[0][0] = 1. For every number in nums, update the DP: for every (s, t) we accumulate ways such that if adding the current number does not exceed k, update dp[s + num][t + 1]. After processing all elements, the answer is the sum for all t of dp[k][t] * (2^(n-t)) modulo 10^9+7.
The main trick is the “swap” of summation order so that we avoid iterating over all subsequences of nums (2^n possibilities) explicitly.