mediumMixed
Sum to Target Solution
Problem Statement
You are given an array of integers and a target sum value. Determine the smallest subset of integers that sum up to the target value.
Examples
Example 1:
Input:nums = [1, 2, 3, 4, 5], target = 9
Output:[2, 3, 4]
Explanation: The subset [2, 3, 4] sums up to 9, which is the target value.
Example 2:
Input:nums = [1, 2, 3, 4, 5], target = 5
Output:[1]
Explanation: The subset [1] sums up to 5, which is the target value.
Example 3:
Input:nums = [1, 2, 3, 4, 5], target = 6
Output:[2]
Explanation: The subset [2] sums up to 6, which is also the target value but with lesser number of herbs which is not stated in the previous example.
Constraints
- The input array may be empty, but the target sum will always be non-negative.
- The target sum value will always be a positive integer.
- The input array will not contain any duplicate integers.
Time: O(2^n * n) Space: O(n)
An optimized approach is to use a dynamic programming approach with a bit mask and a table to store the sum of each subset.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
