BackmediumRecursion Adobe

Galactic Cargo Router Solution

Problem Statement

Given a list of space cargo crates with their respective weights and a target cargo capacity, write a recursive function to generate all unique combinations of crates that sum up to the target capacity.

Example 1
Input
[[1, 5, 9], [2, 3, 5], [3, 7], [4, 6], [2, 8]]
Output
[[1, 5, 9], [2, 3, 5], [3, 7], [4, 6], [2, 8]]

Explanation: Step-by-step: with input [1, 5, 9], [2, 3, 5], [3, 7], [4, 6], [2, 8], we first sort the crates by their weights. Then, we start with the smallest crate and recursively try to add the next smallest crate to the current combination. If the current combination's weight exceeds the target capacity, we backtrack and try the next combination. Finally, we return all unique combinations that sum up to the target capacity.

Example 2
Input
[[1, 2, 3, 9], [1, 2, 4, 8], [1, 3, 4, 7], [1, 3, 5, 6], [1, 4, 5, 5], [2, 3, 4, 6], [2, 3, 5, 5], [2, 4, 4, 5], [3, 3, 4, 5], [3, 4, 4, 4]]
Output
[[1, 2, 3, 9], [1, 2, 4, 8], [1, 2, 5, 7], [1, 3, 4, 7], [1, 3, 5, 6], [1, 4, 5, 5], [2, 3, 4, 6], [2, 3, 5, 5], [2, 4, 4, 5], [3, 3, 4, 5], [3, 4, 4, 4], [1, 5, 9]]

Explanation: Step-by-step: with input [1, 2, 3, 9], [1, 2, 4, 8], [1, 3, 4, 7], [1, 3, 5, 6], [1, 4, 5, 5], [2, 3, 4, 6], [2, 3, 5, 5], [2, 4, 4, 5], [3, 3, 4, 5], [3, 4, 4, 4], we first sort the crates by their weights. Then, we start with the smallest crate and recursively try to add the next smallest crate to the current combination. If the current combination's weight exceeds the target capacity, we backtrack and try the next combination. Finally, we return all unique combinations that sum up to the target capacity.

Constraints

  • 1 <= number of crates <= 20
  • 1 <= weight of each crate <= 50
  • 1 <= target capacity <= 100
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free