Recover original array from all subsets

后端 未结 2 1059
半阙折子戏
半阙折子戏 2020-12-18 10:42

You are given all subset sums of an array. You are then supposed to recover the original array from the subset sums provided.

Every element in the original array is

2条回答
  •  情深已故
    2020-12-18 11:32

    Here's an easy algorithm that doesn't require finding which subset sums to a given number.

    S ← input sequence
    X ← empty sequence

    While S has a non-zero element:

    1. d ← second smallest element of S (the smallest one is always zero)
    2. Insert d in X
    3. N ← empty sequence
    4. While S is not empty:
      • z ← smallest element of S
      • Remove both z and z+d from S (if S does not contain z+d, it's an error; remove only one instance of both z and z+d if there are several).
      • Insert z in N.
    5. S ← N

    Output X.

提交回复
热议问题