Leetcode-3082

Find the Sum of the Power of All Subsequences

Time complexity: $O(nk)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>

const int M = 1'000'000'007;

class Solution {
public:
    int sumOfPower(std::vector<int>& nums, int k) {
        std::vector<long long> dp(k + 1);
        dp[0] = 1;
        
        for (int num : nums) {
            for (int i = k; i >= 0; --i) {
                if (i >= num) {
                    if (dp[i] || dp[i - num]) {
                        dp[i] = (dp[i] * 2 + dp[i - num]) % M;
                    }
                }
                else if (dp[i]) {
                    dp[i] = dp[i] * 2 % M;
                }
            }
        }
        
        return dp.back();
    }
};

Leetcode-3082

Licensed under CC BY-NC-SA 4.0