[Algorithm] Powerset Problem

时间:2024-08-27 21:04:08

By given an array [1,2,3]:

Return all possible combinations. for example: [[], [1], [2], [3], [1, 2].... [1,2,3]]

function combination(ary) {
let result = new Set();
function helper(ary, idx, path = [], result) {
if (idx === ary.length) {
return result.add(path);
} let path_inc_current = [...path, ary[idx]];
let path_not_inc_current = [...path]; helper(ary, idx + , path_inc_current, result);
helper(ary, idx + , path_not_inc_current, result);
} helper(ary, , [], result);
return Array.from(result);
} console.log(JSON.stringify(combination([, , ]))); // [[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]