0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 7
click for more info
No active XP Potion
Accept a Quest
Login to submit answers
Next
ctrl+.
In LockedIn, we have a list of influencers and their respective follower counts. We want to find a subset of influencers whose total follower count is equal to a target number.
This problem is known as the Subset Sum Problem, which is an NP-hard problem. It asks the question, "Can we pick numbers from a list to add up to a target number?"
Complete the subset_sum
function.
It should take a list of integers nums
and an integer target
, and return True
if there exists a subset of nums
that adds up to target
, and False
otherwise. We'll use a recursive, brute-force approach to solve the problem. Brute-force just means we'll try every possible combination to see if any of them add up to the target.
subset_sum(nums, target)
nums
: A list of integers representing the follower counts of influencers.target
: The target sum we want to find a subset for.True
if there exists a subset of nums
that adds up to target
. False
otherwise.
nums
and return its result.find_subset_sum(nums, target, index)
nums
: A list of integers representing the follower counts of influencers.target
: The target sum we want to find a subset for.index
: The index of the current element we're considering.True
if there exists a subset of nums
that adds up to target
. False
otherwise.
target
is 0
, return True
.0
and the target
is not 0
, return False
.target
, call the helper function with the same target
but with the index decremented by 1, and return
the result, we're done.target
and index decremented by 1, and save the result.target
reduced by the value of the current element and the index
decremented by 1True
, return True
. Otherwise, return False
.Focus Editor
Alt+Shift+]
Next Tab
Alt+Shift+[
Become a member to Submit
Become a member to Run
Become a member to view solution