0/1 Knapsack
0/1 Knapsack
Given a backpack with capacity K and a list of n items (each item_i has a size k_i), find a subset of items whose total size equal to K or determine no such subset exists.
Example
Brute Force Approach
We can try all possible subsets, then check their sum. But this will be EXP time. Not desired.
DP Approach
Since the problem is asking for doability (a form of optimization), we can try to do DP on size.
DP Code
The new objective is to pack the bag as full as possible. Just scan the last row in the memo table.
Space Optimization
Notice the problem only has two layers of dependencies. Mod 2 to the access index.
Variant Code
Time & Space Complexity
Time O(nK) Space O(K)
Given an integer array (non-negative), determine if the array can be partitioned into two subsets with equal sum.
This question can framed as the possibility of a tie situation in presidential election given the votes in electoral college.
Example
Brute Force Approach
Because of the nature of a subset, we can get the rest of the items (the other subset) for free. We can first divide the target sum in half, then try all subsets to see if one can sum to target/2
. Like any other exhaustive search, it will have an exponential running time.
Optimization
First step is to define a representation of the problem.
Code
Last updated