# Knapsack, Weight-Only

Prereqs: Backtracking, Memoization

Given a list of weights of `n` items, find all sums that can be formed using their weights.

### Input

• `weights`: A list of `n` positive integers, representing weights of the items

### Output

A list, in any order, of the unique sums that can be obtained by using combinations of the provided weights

### Examples

#### Example 1:

Input:

``1weights = [1, 3, 3, 5]``

Output: `[0, 1, 3, 4, 5, 6, 7, 8, 9, 11, 12]`

Explanation:

We can form all sums from 0 to 12 except 2 and 10. Here is a short explanation for the sums:

• 0: use none of the weights
• 1: use item with weight 1
• 3: use item with weight 3
• 4: use weights 1 + 3 = 4
• 5: use item with weight 5
• 6: use weights 3 + 3 = 6
• 7: use weights 1 + 3 + 3 = 7
• 8: use weights 3 + 5 = 8
• 9: use weights 1 + 3 + 5 = 9
• 11: use weights 3 + 3 + 5 = 11
• 12: use all weights

### Constraints

• `1 <= len(weights) <= 100`
• `1 <= weights[i] <= 100`

## Solution

### Brute Force

A brute force method enumerates all possibilities. We start with a total sum of 0 and process every item by either choosing to include it into our sum or not into our sum. Once no more items are left to process, we can include the final sum in a list of sums. Additionally, we will store these sums in a set since there can be repeating sums.

By going through every possibility, we're generating all possible subsets, so we guarantee that we are also generating all possible sums.

Since there are `n` items, two possibilities each, and it takes `O(1)` to compute each possibility, the final runtime is `O(2^n)`.

The following is the state-space tree for this idea using input `[1, 3, 3, 5]`. Each level `i` of the tree represents a binary decision to include or not include the `ith` number. For example, we have two branches in level `i = 1`, the left branch means not picking the `ith` item `3`, and the right branch means picking it. Here is the code for the idea above:

``````1#include <set> // set
2
3void generate_sums(vector<int> &weights, set<int> &sums, int sum, int n) {
4  if (n == 0) {
5    sums.insert(sum);
6    return;
7  }
8  generate_sums(weights, sums, sum, n - 1);
9  generate_sums(weights, sums, sum + weights[n - 1], n - 1);
10}
11
12vector<int> knapsack_weight_only(vector<int> weights) {
13  set<int> sums;
14  int n = weights.size();
15  generate_sums(weights, sums, 0, n);
16  vector ans(sums.begin(), sums.end());
17  return ans;
18}
19``````
``````1public static void generateSums(List<Integer> weights, Set<Integer> sums, int sum, int n) {
2  if (n == 0) {
4    return;
5  }
6  generateSums(weights, sums, sum, n - 1);
7  generateSums(weights, sums, sum + weights.get(n - 1), n - 1);
8}
9
10public static List<Integer> knapsackWeightOnly(List<Integer> weights) {
11  Set<Integer> sums = new HashSet<>();
12  int n = weights.size();
13  generateSums(weights, sums, 0, n);
14  List<Integer> ans = new ArrayList<>();
16  return ans;
17}
18``````
``````1function generateSums(weights, sums, sum, n) {
2  if (n === 0) {
4    return;
5  }
6  generateSums(weights, sums, sum, n - 1);
7  generateSums(weights, sums, sum + weights[n - 1], n - 1);
8}
9
10function knapsackWeightOnly(weights) {
11  var sums = new Set();
12  var n = weights.length;
13  generateSums(weights, sums, 0, n);
14  return Array.from(sums);
15}
16``````
``````1def generate_sums(weights, sums, sum, n):
2  if n == 0:
4    return
5  generate_sums(weights, sums, sum, n - 1)
6  generate_sums(weights, sums, sum + weights[n - 1], n - 1)
7
8def knapsack_weight_only(weights):
9  sums = set()
10  n = len(weights)
11  generate_sums(weights, sums, 0, n)
12  return list(sums)
13``````

## Top-down Dynamic Programming

First, the "top-down" solution is, basically, the brute force solution but with memoization. We store results that have already been computed and return them once needed. But in precisely what way should we store/represent the data? Going back to the idea of dynamic programming, we should consider what is important so far and if any of the information has been recomputed.

### Memoization, identifying the state

To memoize, we need to find the duplicate subtrees in the state-space tree. Notice that the duplicate subtrees are of the same level for this problem. This isn't a coincidence.

Unlike Word Break and Decode Ways in the backtracking section, the items in the knapsack problem can only be used once.

Consider `Node A` and `Node B` in the tree: `Node B`'s subtree has leaf values of `3` and `8`. And `Node A`'s subtree has leaf values of `3, 8, 6, 11`. They are clearly not the same subtree. This is because the meaning of a node's value is the weight sum by considering items from `0` to `i`.

Therefore, the state we need to memoize consists of the level/depth of the node and the node value itself. We will use `(i, sum)` to denote this.

Thus, we will store a 2D boolean array `memo` where `memo[i][sum] = true` if the `(i, sum)` pair has already been computed and `false` otherwise. The size of the array is `n * total_sum` where `n` is the number of items and `total_sum` is the weight sum of all items. We need a slot for each possible weight we can make up, and all the possible weights are in the range of `0` to `total_sum`.

Here is the implementation of the idea:

``````1void generate_sums(vector<int> &weights, set<int> &sums, int sum, int n, vector<vector<bool>> &memo) {
2  if (memo[n][sum]) {
3    return;
4  }
5  if (n == 0) {
6    sums.insert(sum);
7    return;
8  }
9  generate_sums(weights, sums, sum, n - 1, memo);
10  generate_sums(weights, sums, sum + weights[n - 1], n - 1, memo);
11  memo[n][sum] = true;
12}
13
14vector<int> knapsack_weight_only(vector<int> weights) {
15  set<int> sums;
16  int n = weights.size();
17  // find total sum of all items
18  int total_sum = 0;
19  for (int weight : weights) {
20    total_sum += weight;
21  }
22  // initialize memo table to store if result has been calculated
23  vector<vector<bool>> memo(n + 1, vector<bool>(total_sum + 1, false));
24  generate_sums(weights, sums, 0, n, memo);
25  vector ans(sums.begin(), sums.end());
26  return ans;
27}
28``````
``````1public static void generateSums(List<Integer> weights, Set<Integer> sums, int sum, int n, boolean[][] memo) {
2  if (memo[n][sum]) {
3    return;
4  }
5  if (n == 0) {
7    return;
8  }
9  generateSums(weights, sums, sum, n - 1, memo);
10  generateSums(weights, sums, sum + weights.get(n - 1), n - 1, memo);
11  memo[n][sum] = true;
12}
13
14public static List<Integer> knapsackWeightOnly(List<Integer> weights) {
15  Set<Integer> sums = new HashSet<>();
16  int n = weights.size();
17  // find total sum of all items
18  int totalSum = 0;
19  for (int weight : weights) {
20    totalSum += weight;
21  }
22  // initialize memo table to store if result has been calculated
23  boolean[][] memo = new boolean[n + 1][totalSum + 1];
24  for (int i = 0; i < n + 1; i++) {
25    Arrays.fill(memo[i], false);
26  }
27  generateSums(weights, sums, 0, n, memo);
28  List<Integer> ans = new ArrayList<>();
30  return ans;
31}
32``````
``````1function generateSums(weights, sums, sum, n, memo) {
2  if (memo[n][sum]) {
3    return;
4  }
5  if (n === 0) {
7    return;
8  }
9  generateSums(weights, sums, sum, n - 1, memo);
10  generateSums(weights, sums, sum + weights[n - 1], n - 1, memo);
11  memo[n][sum] = true;
12}
13
14function knapsackWeightOnly(weights) {
15  var sums = Set();
16  var n = weights.length;
17  // find total sum of all items
18  var totalSum = 0;
19  for (let weight of weights) {
20    totalSum += weight;
21  }
22  // initialize memo table to store if result has been calculated
23  var memo = new Array(n + 1);
24  for (let i = 0; i < n + 1; i++) {
25    memo[i] = new Array(totalSum + 1);
26    for (let j = 0; j < totalSum + 1; j++) {
27      memo[i][j] = false;
28    }
29  }
30  generateSums(weights, sums, 0, n, memo);
31  return Array.from(sums);
32}
33``````
``````1def generate_sums(weights, sums, sum, n, memo):
2  if memo[n][sum]:
3    return
4  if n == 0:
6    return
7  generate_sums(weights, sums, sum, n - 1, memo)
8  generate_sums(weights, sums, sum + weights[n - 1], n - 1, memo)
9  memo[n][sum] = True
10
11def knapsack_weight_only(weights):
12  sums = set()
13  n = len(weights)
14  # find total sum of weights
15  total_sum = sum(weights)
16  memo = [[False for _ in range(total_sum + 1)] for _ in range(n + 1)]
17  generate_sums(weights, sums, 0, n, memo)
18  return list(sums)
19``````

Since there are `n * totalSum` states, each state depends on `O(1)` subproblems, and each state takes `O(1)` to compute, and the final runtime is `O(n * totalSum)`. Having `n * totalSum` different states also gives us a memory complexity of `O(n * totalSum)` with this approach.

## Bottom-up Dynamic Programming

Now let's talk about the "bottom-up" solution. Recall that the idea of any bottom-up solution is to start from the smallest cases and work your way up to larger problems. The solution starts from the base case: 0 items can make up a knapsack of weight 0. Then, we can build up more plausible weights by combining the existing plausible weights by a new item. We continue this process until we get to our desired solution, that is, when we have used up all the weights. Thus, by looping through each item, we determine which sums we can construct based on if there exists a smaller sum that we can build on top of. For example, suppose we already built all possible sums using `[1, 3, 3]`, and we wanted to know which sums we can build using all of `[1, 3, 3, 5]` now. The following is an illustration of this idea:

And here's the code for the iterative/bottom-up solution:

``````1vector<int> knapsack_weight_only(vector<int> weights) {
2  int n = weights.size();
3  int total_sum = 0;
4  for (int weight : weights) {
5    total_sum += weight;
6  }
7  vector<vector<bool>> dp(n + 1, vector<bool>(total_sum + 1, false));
8  dp = true;
9  for (int i = 1; i <= n; i++) {
10    for (int w = 0; w <= total_sum; w++) {
11      // vertical blue arrow in the above slides
12      dp[i][w] = dp[i][w] || dp[i - 1][w];
13      // diagonal blue arrow in the above slides
14      if (w - weights[i - 1] >= 0) { // make sure current item's weight is smaller than the target weight w
15        dp[i][w] = dp[i][w] || dp[i - 1][w - weights[i - 1]];
16      }
17    }
18  }
19  vector<int> ans;
20  // check the last row for all possible answers
21  for (int w = 0; w <= total_sum; w++) {
22    if (dp[n][w]) {
23      ans.emplace_back(w);
24    }
25  }
26  return ans;
27}
28``````
``````1public static List<Integer> knapsackWeightOnly(List<Integer> weights) {
2  int n = weights.size();
3  int totalSum = 0;
4  for (int weight : weights) {
5    totalSum += weight;
6  }
7  boolean[][] dp = new boolean[n + 1][totalSum + 1];
8  dp = true;
9  for (int i = 1; i <= n; i++) {
10    for (int w = 0; w <= totalSum; w++) {
11      // vertical blue arrow in the above slides
12      dp[i][w] = dp[i][w] || dp[i - 1][w];
13      // diagonal blue arrow in the above slides
14      if (w - weights.get(i - 1) >= 0) { // make sure current item's weight is smaller than the target weight w
15        dp[i][w] = dp[i][w] || dp[i - 1][w - weights.get(i - 1)];
16      }
17    }
18  }
19  List<Integer> ans = new ArrayList<>();
20  // check the last row for all possible answers
21  for (int w = 0; w <= totalSum; w++) {
22    if (dp[n][w]) {
24    }
25  }
26  return ans;
27}
28``````
``````1function knapsackWeightOnly(weights) {
2  var n = weights.length;
3  var totalSum = 0;
4  for (let weight in weights) {
5    totalSum += weight;
6  }
7  var dp = new Array(n + 1);
8  for (let i = 0; i <= n; i++) {
9    dp[i] = new Array(totalSum + 1);
10    for (let w = 0; w <= totalSum; w++) {
11      dp[i][w] = false;
12    }
13  }
14  dp = true;
15  for (let i = 1; i <= n; i++) {
16    for (let w = 0; w <= totalSum; w++) {
17      // vertical blue arrow in the above slides
18      dp[i][w] = dp[i][w] || dp[i - 1][w];
19      // diagonal blue arrow in the above slides
20      if (w - weights[i - 1] >= 0) { // make sure current item's weight is smaller than the target weight w
21        dp[i][w] = dp[i][w] || dp[i - 1][w - weights[i - 1]];
22      }
23    }
24  }
25  var ans = [];
26  // check the last row for all possible answers
27  for (let w = 0; w <= totalSum; w++) {
28    if (dp[n][w]) {
29      ans.push(w);
30    }
31  }
32  return ans;
33}
34``````
``````1def knapsack_weight_only(weights):
2  n = len(weights)
3  total_sum = sum(weights)
4  dp = [[False for _ in range(total_sum + 1)] for _ in range(n + 1)]
5  dp = True
6  for i in range(1, n + 1):
7    for w in range(0, total_sum + 1):
8      # vertical blue arrow in the above slides
9      dp[i][w] = dp[i][w] or dp[i - 1][w]
10      # diagonal blue arrow in the above slides
11      if w - weights[i - 1] >= 0: # make sure the current item's weight is smaller than the target weight w
12        dp[i][w] = dp[i][w] or dp[i - 1][w - weights[i - 1]]
13  ans = []
14  # check the last row for all possible answers
15  for w in range(0, total_sum + 1):
16    if dp[n][w]:
17      ans.append(w)
18  return ans
19``````

The final runtime of this program is `O(n * totalSum)` because there is `O(n * totalSum)` states, each state depends on `O(1)` subproblems, and each state takes `O(1)` to compute.

### Space Optimization (optional)

Finally, there is a slight memory optimization that we can perform. Observe that `dp[i][w]` depends on, at most, the previous row (`dp[i][w] = dp[i][w] || dp[i - 1][w - weights[i - 1]]`). Thus, instead of storing the entire 2D array, we can simply store two 1D arrays, one to keep track of the previous and one to for the current. This improves our memory usage from `O(n * totalSum)` to `O(totalSum)`.

Here's the implementation:

``````1from typing import List
2
3def knapsack_weight_only(weights: List[int]) -> int:
4  n = len(weights)
5  total_sum = sum(weights) # get maximum sum possible
6
7  # initialize 2 1D arrays (2 * N array)
8  dp = [[False for _ in range(total_sum + 1)] for _ in range(2)]
9  dp = True
10  for i in range(1, n + 1):
11    for w in range(0, total_sum + 1):
12      # current row is dp, previous row is dp
13      dp[w] = dp[w] or dp[w]
14      if w - weights[i - 1] >= 0:
15        dp[w] = dp[w] or dp[w - weights[i - 1]]
16    for w in range(0, total_sum + 1): # update previous row to current row
17      dp[w] = dp[w]
18
19  # dp[w] = true if `w` is an attainable weight, thus add it to our answer
20  ans = []
21  for w in range(0, total_sum + 1):
22    if dp[w]:
23      ans.append(w)
24  return ans
25
26if __name__ == '__main__':
27    weights = [int(x) for x in input().split()]
28    res = knapsack_weight_only(weights)
29    res.sort()
30    for i in range(len(res)):
31      print(res[i], end='')
32      if i != len(res) - 1:
33        print(' ', end='')
34    print()
35``````
``````1import java.util.ArrayList;
2import java.util.Arrays;
3import java.util.Collections;
4import java.util.List;
5import java.util.Scanner;
6import java.util.stream.Collectors;
7
8class Solution {
9    public static List<Integer> knapsackWeightOnly(List<Integer> weights) {
10      int n = weights.size();
11      int totalSum = 0; // get maximum sum possible
12      for (int weight : weights) {
13        totalSum += weight;
14      }
15
16      // initialize 2 1D arrays (2 * N array)
17      boolean[][] dp = new boolean[totalSum + 1];
18      dp = true;
19      for (int i = 1; i <= n; i++) {
20        for (int w = 0; w <= totalSum; w++) {
21          // current row is dp, previous row is dp
22          dp[w] = dp[w] || dp[w];
23          if (w - weights.get(i - 1) >= 0) {
24            dp[w] = dp[w] || dp[w - weights.get(i - 1)];
25          }
26        }
27        for (int w = 0; w <= totalSum; w++) { // update previous row to current row
28          dp[w] = dp[w];
29        }
30      }
31      // dp[w] = true if `w` is an attainable weight, thus add it to our answer
32      List<Integer> ans = new ArrayList<>();
33      for (int w = 0; w <= totalSum; w++) {
34        if (dp[w]) {
36        }
37      }
38      return ans;
39    }
40
41    public static List<String> splitWords(String s) {
42        return s.isEmpty() ? List.of() : Arrays.asList(s.split(" "));
43    }
44
45    public static void main(String[] args) {
46        Scanner scanner = new Scanner(System.in);
47        List<Integer> weights = splitWords(scanner.nextLine()).stream().map(Integer::parseInt).collect(Collectors.toList());
48        scanner.close();
49        List<Integer> res = knapsackWeightOnly(weights);
50        Collections.sort(res);
51        for (int i = 0; i < res.size(); i++) {
52          System.out.print(res.get(i));
53          if (i != res.size() - 1) {
54            System.out.print(" ");
55          }
56        }
57        System.out.println();
58    }
59}
60``````
``````1#include <algorithm> // copy, sort
2#include <iostream> // boolalpha, cin
3#include <iterator> // back_inserter, istream_iterator
4#include <sstream> // istringstream
5#include <string> // getline, string
6#include <vector> // vector
7
8using namespace std;
9
10vector<int> knapsack_weight_only(vector<int> weights) {
11  int n = weights.size();
12  int total_sum = 0;
13  for (int weight : weights) {
14    total_sum += weight;
15  }
16  vector<vector<bool>> dp(2, vector<bool>(total_sum + 1, false));
17  dp = true;
18  for (int i = 1; i <= n; i++) {
19    for (int w = 0; w <= total_sum; w++) {
20      dp[w] = dp[w] || dp[w];
21      if (w - weights[i - 1] >= 0) {
22        dp[w] = dp[w] || dp[w - weights[i - 1]];
23      }
24    }
25    for (int w = 0; w <= total_sum; w++) { // update previous row to current row
26      dp[w] = dp[w];
27    }
28  }
29
30  // dp[w] = true if `w` is an attainable weight, thus add it to our answer
31  vector<int> ans;
32  for (int w = 0; w <= total_sum; w++) {
33    if (dp[w]) {
34      ans.emplace_back(w);
35    }
36  }
37  return ans;
38}
39
40template<typename T>
41std::vector<T> get_words() {
42    std::string line;
43    std::getline(std::cin, line);
44    std::istringstream ss{line};
45    ss >> std::boolalpha;
46    std::vector<T> v;
47    std::copy(std::istream_iterator<T>{ss}, std::istream_iterator<T>{}, std::back_inserter(v));
48    return v;
49}
50
51int main() {
52    std::vector<int> weights = get_words<int>();
53    std::vector<int> res = knapsack_weight_only(weights);
54    std::sort(res.begin(), res.end());
55    for (int i = 0; i < res.size(); i++) {
56      cout << res[i];
57      if (i != res.size() - 1) {
58        cout << " ";
59      }
60    }
61    cout << "\n";
62}
63``````

The space optimization is a nice trick but it's also easy to get the row swapping wrong. It's great to mention this to the interviewer after you have perfected your regular solution and confirm that with the interviewer. Pre-mature optimization is the root of all evil in software engineering.

## Steps to work through a DP problem:

We can see from this example the top-down and bottom-up are essentially equivalent.

Remember: DP = DFS + pruning + memoization.

Steps to solve a DP problem:

• brute force
• draw the state-space tree
• dfs on the state-space tree
• prune if possible
• memo
• find the duplicate subtrees
• bottom-up (if you want to)
• optional space optimzation

Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.

TA 👨‍🏫