查找数组中所有可能的子集组合?

2022-01-31 00:00:00 arrays subset javascript

我需要获取一个数组的所有可能子集,其中包含最少 2 个项目和未知的最大值.谁能帮帮我?

I need to get all possible subsets of an array with a minimum of 2 items and an unknown maximum. Anyone that can help me out a bit?

假设我有以下数组:

[1, 2, 3]

我如何得到这个?

[
    [1, 2],
    [1, 3],
    [2, 3],
    [1, 2, 3]
]

推荐答案

盗取后this JavaScript 组合生成器,我添加了一个参数来提供导致的最小长度,

After stealing this JavaScript combination generator, I added a parameter to supply the minimum length resulting in,

var combine = function(a, min) {
    var fn = function(n, src, got, all) {
        if (n == 0) {
            if (got.length > 0) {
                all[all.length] = got;
            }
            return;
        }
        for (var j = 0; j < src.length; j++) {
            fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
        }
        return;
    }
    var all = [];
    for (var i = min; i < a.length; i++) {
        fn(i, a, [], all);
    }
    all.push(a);
    return all;
}

要使用,提供一个数组,以及所需的最小子集长度,

To use, supply an array, and the minimum subset length desired,

var subsets = combine([1, 2, 3], 2);

输出是,

[[1, 2], [1, 3], [2, 3], [1, 2, 3]]

相关文章