Recover original array from all subsets

后端 未结 2 1052
半阙折子戏
半阙折子戏 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.

提交回复
热议问题