Subset Sum—Dynamic Programming
Discover the different techniques used to solve the subset sum problem efficiently.
Dynamic programming algorithm for subset sum problem
Recall that the subset sum problem asks whether any subset of a given array of positive integers sums to a given integer . In a previous lesson, we developed a recursive subset sum algorithm that can be reformulated as follows. Fix the original input array and define the boolean function if and only if some subset of sums to
We need to compute . This function satisfies the following recurrence:
Transforming recurrence into dynamic programming algorithm
We can transform this recurrence into a dynamic programming algorithm following the usual boilerplate.
- Subproblems: Each subproblem is described by an integer such that , and an integer . However, subproblems with are trivial, so it seems rather silly to memoize them. Indeed, we can modify the recurrence so that those subproblems never arise:
- Data structure: We can memoize our recurrence into a two-dimensional array , where stores the value of .
- Evaluation order: Each entry depends on at most two other entries, both of the form . So we can fill the array by considering rows from bottom to top in the outer loop and considering the elements in each row in arbitrary order in the inner loop.
- Space and time: The memoization structure uses space. If and are already known, we can compute in constant time, so the algorithm runs in time.
Here is the resulting dynamic programming algorithm:
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy