Given a set S, find all the maximal subsets whose sum <= k

后端 未结 6 1445
感动是毒
感动是毒 2021-02-14 21:52

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,

6条回答
  •  太阳男子
    2021-02-14 21:59

    I am sorry for chipping in so late. But how about doing this?

    1) Build a MIN-HEAP structure from the given array/set

    2) traverse the structure from the root and keep subtracting the value at the node that you visit. Once you exceed the required sum (curr_sum > k), output this path, backtrack to the parent and take another path (this can be done recursively).

    3) If backtracking takes you back to the original node that you started from, implement the entire algorithm recursively from root->left node.

    4) Do the same two steps (2) and (3) above but with a MAX-HEAP now.

    I am new to algorithms and data structures, and have only started reading Intro to Algos-Cormen. This might be a faulty solution, but I would be more than happy if anyone points out the fault to me :)

提交回复
热议问题