101 Logo
onenoughtone

Problem Statement

Hiking Backpack Packer

You're planning a hiking trip in the beautiful Rocky Mountains. As an experienced hiker, you know that carrying the right amount of weight is crucial—too little and you might not have all the essentials, too much and you'll be exhausted before reaching the summit.

You have a collection of hiking gear, each with its own weight (in pounds). Your backpack has a weight capacity that you don't want to exceed, but you want to maximize the total weight to ensure you're bringing as much useful gear as possible.

Your task is to determine if there's a subset of your gear whose weights sum exactly to your backpack's capacity. This will help you pack efficiently without overloading or underutilizing your backpack.

Examples

Example 1:

Input: gearWeights = [2, 3, 7, 8, 10], capacity = 11
Output: true
Explanation: You can pack items weighing 3 and 8 pounds, which sum to 11 pounds.

Example 2:

Input: gearWeights = [1, 3, 5], capacity = 10
Output: false
Explanation: There's no combination of weights that sum exactly to 10 pounds.

Example 3:

Input: gearWeights = [4, 2, 3, 5, 6], capacity = 9
Output: true
Explanation: You can pack items weighing 4 and 5 pounds, which sum to 9 pounds.

Constraints

  • The number of gear items will be between 1 and 100.
  • Each gear weight will be a positive integer less than 100.
  • The backpack capacity will be a positive integer less than 10,000.
  • The function should return true if there's a subset of weights that sum exactly to the capacity, and false otherwise.

Problem Breakdown

To solve this problem, we need to:

  1. This problem is a classic example of the Subset Sum problem, which is NP-complete.
  2. The recursive approach naturally models the decision of whether to include or exclude each item, making it a perfect fit for the Selection Pattern of recursion.
  3. Dynamic programming can be used to optimize the solution by avoiding redundant calculations.
  4. The problem can also be viewed as a special case of the Knapsack problem, where each item's value is equal to its weight.
ProblemSolutionCode
101 Logo
onenoughtone