2
public boolean canDistribute(int[] nums, int[] quantity) {4
// Use a map to count the numbers, ex: nums:[5,7,4,7,4,7] -> {5:1, 7:3, 4:2}5
Map<Integer, Integer> freq = new HashMap<>();6
for (int num : nums) freq.put(num, freq.getOrDefault(num, 0) + 1);8
// Turn values of the map into array, ex: {5:1, 7:3, 4:2} -> [1, 3, 2]9
int[] dist = new int[freq.size()];11
for (int f : freq.values()) dist[idx++] = f;13
// Fullfill the quantities from the biggest quantity to the smallest.14
// If the bigger quantity can't be filled, the program will stop as early as possible.15
Arrays.sort(quantity);16
return rec(dist, quantity, quantity.length - 1);19
// try to fullfill the j-th order quantity20
private boolean rec(int[] dist, int[] quantity, int j) {22
// stop condition. We've fulfilled all the order quantities.23
if (j == -1) return true;25
Set<Integer> used = new HashSet<>();26
for (int i = 0; i < dist.length; ++i) {28
// Use a set to make sure that29
// we don't distribute from the same amount to this j-th order for more than once.30
// With this check, the program reduces from 97ms to 25 ms.31
if (dist[i] >= quantity[j] && used.add(dist[i])) {32
dist[i] -= quantity[j];33
if (rec(dist, quantity, j - 1)) return true;34
dist[i] += quantity[j];