This is a Facebook interview question I came across at an online portal.
Given a set S, find all the maximal subsets whose sum <= k. For example, if S = {1, 2, 3, 4,
I have some idea - you need a tree.
If you have given input of {1, 2, 3, 4, 5}
, and you're searching for maximal subsets - you should build a tree starting from the biggest numbers, and allways expand while sum <= k
(so don't stop on 4-2, but go down to 1 to get 4-2-1).
So, nodes starting from 5 would be: 5-1 / 5-2 - only those 2 have sum <= 7
starting from 4: 4-3 / 4-2-1 / 4-1 (subset of previous)
starting from 3: 3-2-1 / 3-1 (subset of previous)
starting from 2: 2-1 (subset of 3-2-1)
starting from 1: 1 (subset of 2-1)
Then you can sort valid outputs and get {1, 2, 3} {1, 2, 4} {1, 5} {2, 5} {3, 4}