Recover original array from all subsets

后端 未结 2 1045
半阙折子戏
半阙折子戏 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:25

    Say S is the subset sum array and A is the original array. I'm assuming S is sorted.

    |A| = log2(|S|)
    S[0] = 0
    S[1] = A[0]
    S[2] = A[1]
    S[3] = EITHER A[2] OR A[0] + A[1].
    

    In general, S[i] for i >= 3 is either an element of A or a combination of the elements of A that you've already encountered. When processing S, skip once per combination of known elements of A that generate a given number, add any remaining numbers to A. Stop when A gets to the right size.

    E.g., if A=[1,2,7,8,9] then S will include [1,2,1+2=3,...,1+8=9, 2+7=9,9,...]. When processing S we skip over two 9s because of 1+8 and 2+7, then see a third 9 which we know must belong to A.

    E.g., if S=[0,1,1,2,8,9,9,10] then we know A has 3 elements, that the first 2 elements of A are [1,1], when we get to 2 we skip it because 1+1=2, we append 8 and we're done because we have 3 elements.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题