3082. Find the Sum of the Power of All Subsequences
Description
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 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 109 + 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]has2subsequences withsum == 3:[1,2,3]and[1,2,3]. - The subsequence
[1,2,3]has1subsequence withsum == 3:[1,2,3]. - The subsequence
[1,2,3]has1subsequence withsum == 3:[1,2,3]. - The subsequence
[1,2,3]has1subsequence withsum == 3:[1,2,3]. - The subsequence
[1,2,3]has1subsequence withsum == 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 withsum == 5:[2,3,3]and[2,3,3]. - The subsequence
[2,3,3]has 1 subsequence withsum == 5:[2,3,3]. - The subsequence
[2,3,3]has 1 subsequence withsum == 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] <= 1041 <= k <= 100
Solutions
Solution: Dynamic Programming
- Time complexity: O(nk)
- Space complexity: O(nk)
JavaScript
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
const sumOfPower = function (nums, k) {
const MODULO = BigInt(10 ** 9 + 7);
const n = nums.length;
const dp = Array.from({ length: n }, () => new Array(k + 1).fill(-1));
const getSubsequences = (index, sum) => {
if (sum === k) {
return modPow(2n, BigInt(n - index), MODULO);
}
if (sum > k || index >= n) return 0n;
if (dp[index][sum] !== -1) return dp[index][sum];
const skip = getSubsequences(index + 1, sum);
const pick = getSubsequences(index + 1, sum + nums[index]);
const result = (pick + 2n * skip) % MODULO;
dp[index][sum] = result;
return result;
};
return Number(getSubsequences(0, 0));
};
function modPow(base, exp, mod) {
let result = 1n;
while (exp) {
if (exp % 2n) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exp /= 2n;
}
return result;
}