Вы можете сделать это так:
const arr_origin = [2,4,5,7,2,4,5,20];
const arr_unique = [...new Set(arr_origin)];
const cover_num = 10;
var closest_sum = arr_origin.reduce((a,b) => a+b, 0);
var arr_optimal = arr_unique;
find([], 0);
function find(arr_now, idx) {
const sum = arr_now.reduce((a,b) => a+b, 0);
if ( (cover_num <= sum && sum < closest_sum) ||
(cover_num <= sum && sum == closest_sum && arr_now.length < arr_optimal.length) )
{
closest_sum = sum;
arr_optimal = arr_now;
}
if (idx < arr_unique.length) {
// skip this element
find(arr_now, idx+1);
// add this element into array
var arr_new = arr_now.slice(0);
arr_new.push(arr_unique[idx]);
find(arr_new, idx+1);
}
}
Это даст:
// [2, 4, 5, 7], to cover 10 => [4,7], 11
// [5, 6, 3, 6, 20], to cover 18 => [20], 20
// [2,4,5,7,2,4,5,20], to cover 10 => [4,7], 11
Спасибо