5853. Find Array Given Subset Sums
5853. Find Array Given Subset Sums
Description
Solution
Firstly, let’s think about a easier question—If sums
‘s elements are all positive, how would you solve this?
- Obviously, the minimum one
m
is the front one in theans
array. - How to find the next answers?
- Delete all subset in
sums
fromans
array, which should be $2^{ans.size()-1}$ elements to be deleted - How to do this in programming?
- In each iteration, use a
mask
to mark the combination ofans
‘s numbers, note that we just need to delete the combination of new found number and other’s - Use
multiset
- In each iteration, use a
- Delete all subset in
Then how to apply this to this problem? We can add up a positive number to convert the array into with all positive one. Especially, we add the number of -(sum of all negative number)
. Then we apply the algorithm described above into new one, then we could get a temp ans
array.
- How to convert the
ans
into what we want?- We notice that after round up,
sums
array always starts with 0, then the next value is the largest negative value (Because the next value should be like (a + b + c - a- b- c -d), d is exactly the largest negative value) - So in the
ans
array, if we could find a serial of numbers which sum up tom
, which means we could negate them them to make whole array sum up to0
. Then we negate them.
- We notice that after round up,
Code
1 | class Solution { |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.