Count Multiset Sum (Knapsacks) by Dynamic Programming Algorithm


Given a list of unique positive integers nums and a positive integer k, return the number of unique combinations that sum up to k. You may reuse numbers when creating combinations.

Constraints
n ≤ 25 where n is the length of nums
1 ≤ nums[i] ≤ 250 for all 0 ≤ i < n 1 ≤ k ≤ 500 Example 1 Input nums = [1, 2, 3] k = 2 Output 2 Explanation We can make 2 with [1, 1] and [2].

Dynamic Programming Algorithm to Count Multiset Sum (Knapsacks)

Given N items which have corresponding weights, and the knapsack capacity is k. Find the number of ways to pack the knapsack full with items. We can do this with Backtracking algorithm where we simulate the packing process: Count Multiset Sum (Knapsacks) by Recursive BackTracking Algorithm

We can also solve this using Dynamic Programming Algorithm. Let dp[i] represent the number of ways to pack with items that sum up to i:

tex_b0864df8b22563c7cbd47772ffaddc19 Count Multiset Sum (Knapsacks) by Dynamic Programming Algorithm algorithms c / c++ dynamic programming Dynamic Programming Knapsack Problems math
tex_0cf05920b2ee8df60dc2d0330e30262a Count Multiset Sum (Knapsacks) by Dynamic Programming Algorithm algorithms c / c++ dynamic programming Dynamic Programming Knapsack Problems math where n is the weights

The following time complexity is O(KN) – bottom up Dynamic Programming.

1
2
3
4
5
6
7
8
9
10
11
12
int countMultisetSum(vector<int>& nums, int k) {
    vector<int> dp(k + 1, 0);
    dp[0] = 1;
    for (auto &n: nums) {
        for (int i = 1; i <= k; ++ i) {        
            if (n <= i) {
                dp[i] += dp[i - n];
            }
        }
    }
    return dp.back();
}
int countMultisetSum(vector<int>& nums, int k) {
    vector<int> dp(k + 1, 0);
    dp[0] = 1;
    for (auto &n: nums) {
        for (int i = 1; i <= k; ++ i) {        
            if (n <= i) {
                dp[i] += dp[i - n];
            }
        }
    }
    return dp.back();
}

See also: Dynamic Programming Algorithm to Solve the Poly Knapsack (Ubounded) Problem

Knapsack Problems

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
394 words
Last Post: Teaching Kids Programming - Longest Consecutive Run of 1s in Binary
Next Post: Remove Duplicate Numbers by using a Hash Map

The Permanent URL is: Count Multiset Sum (Knapsacks) by Dynamic Programming Algorithm

Leave a Reply