Find the Sum of the Power of All Subsequences Problem
Description
LeetCode Problem 3082.
You are given an integer array nums of length n and a positive integer k.
The power of an array of integers is defined as the number of subsequences with their sum equal to k.
Return the sum of power of all subsequences of nums.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [1,2,3], k = 3
Output: 6
Explanation:
There are 5 subsequences of nums with non-zero power:
- The subsequence [1,2,3] has 2 subsequences with sum == 3: [1,2,3] and [1,2,3].
- The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
- The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
- The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
- The subsequence [1,2,3] has 1 subsequence with sum == 3: [1,2,3].
Hence the answer is 2 + 1 + 1 + 1 + 1 = 6.
Example 2:
Input: nums = [2,3,3], k = 5
Output: 4
Explanation:
There are 3 subsequences of nums with non-zero power:
- The subsequence [2,3,3] has 2 subsequences with sum == 5: [2,3,3] and [2,3,3].
- The subsequence [2,3,3] has 1 subsequence with sum == 5: [2,3,3].
- The subsequence [2,3,3] has 1 subsequence with sum == 5: [2,3,3].
Hence the answer is 2 + 1 + 1 = 4.
Example 3:
Input: nums = [1,2,3], k = 7
Output: 0
Explanation: There exists no subsequence with sum 7. Hence all subsequences of nums have power = 0.
Constraints:
1 <= n <= 1001 <= nums[i] <= 10^41 <= k <= 100
Solution
Approach: Dynamic Programming
Counting pairs (S, T) with T a subsequence of S summing to k is the same as choosing, for every number, one of three roles: not in S, in S only, or in both S and T.
Let f[i][j] be the number of ways to decide the first i numbers so that the numbers in T sum to j. With f[0][0] = 1, for the i-th number x:
f[i][j] = 2 * f[i-1][j] + f[i-1][j-x] (the last term only when j >= x)
The first term covers "not in S" and "in S only", the second "in both". Everything is taken modulo 10^9 + 7. The answer is f[n][k].
Complexity: O(n * k) time and space.
class Solution:
def sumOfPower(self, nums: List[int], k: int) -> int:
mod = 10**9 + 7
n = len(nums)
f = [[0] * (k + 1) for _ in range(n + 1)]
f[0][0] = 1
for i, x in enumerate(nums, 1):
for j in range(k + 1):
f[i][j] = f[i - 1][j] * 2 % mod
if j >= x:
f[i][j] = (f[i][j] + f[i - 1][j - x]) % mod
return f[n][k]