[LeetCode] Find Array Given Subset Sums

1982. Find Array Given Subset Sums

You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order).

Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them.

An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0.

Note: Test cases are generated such that there will always be at least one correct answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#define all(a) begin(a), end(a)
class Solution {
vector<int> extractSubsetOf(vector<int>& A, int k) {
vector<int> res;
unordered_map<int,int> mp;
for(auto& n : A) mp[n]++;
int n = A.size();
int i = k >= 0 ? n - 1 : 0;
bool self = false;
while(0 <= i and i < n) {
if(mp[A[i]]) {
if(A[i] == k) self = true;
if(!mp[A[i]-k]) return {INT_MIN};
mp[A[i]-k]--;
mp[A[i]]--;
res.push_back(A[i]-k);
}
i += (k >= 0? -1 : 1);
}
if(!self) return {INT_MIN};
sort(all(res));
return res;
}
bool expectSubset(vector<int>& subset) {
if(subset.size() & 1) {
if(subset.size() > 1) return false;
return subset[0] == 0;
}
return true;
}
bool helper(vector<int> A, vector<int>& res, int p) {
if(p == res.size()) return true;
int n = A.size();
int gap = A[n-1] - A[n-2];

auto poSubset = extractSubsetOf(A, gap);
if(expectSubset(poSubset) and helper(poSubset, res, p + 1)) {
res[p] = gap;
return true;
}

auto neSubset = extractSubsetOf(A, -gap);
if(expectSubset(neSubset) and helper(neSubset, res, p + 1)) {
res[p] = -gap;
return true;
}

return false;
}
public:
vector<int> recoverArray(int n, vector<int>& sums) {
sort(all(sums));
vector<int> res(n);
helper(sums, res, 0);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/27/PS/LeetCode/find-array-given-subset-sums/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.