Overview
This asks a simple YES/NO question: Can we pick some elements from the array such that they sum exactly to `target`? It's a classic subset selection problem.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Determine if there is a subset of the given array whose elements sum up to a specific target. This is a foundational 0/1 Knapsack problem.
This asks a simple YES/NO question: Can we pick some elements from the array such that they sum exactly to `target`? It's a classic subset selection problem.
We use a 1D boolean array where `dp[j]` is `true` if a subset with sum `j` exists. It's initialized to `false`, except `dp[0] = true`.
For each number `num`, if we can reach sum `j - num`, then we can definitely reach sum `j` by just adding `num`. So, `dp[j] = dp[j] || dp[j - num]`.
When compressing from a 2D matrix down to a 1D array, you MUST iterate the inner loop backwards. If you iterate forwards, you might accidentally use the same `num` multiple times!