function dfs(idx, rest, stack) {
if (rest) {
if (idx) {
idx -= 1;
dfs(idx, rest, stack);
if (rest < data[idx]) return;
stack.push(data[idx]);
dfs(idx, rest - data[idx], stack)
stack.pop();
}
} else
console.log(stack);
}
const data = [1, 2, 3, 8, 7, 4].reverse(), n = 10;
dfs(data.length, n, []);