您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页js获取数组的所有子集

js获取数组的所有子集

来源:伴沃教育

使用javascript获取一个数组的所有子集,比如:
[1, 2, 3] 的所有子集是:
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]

解题思路:

假设res是一个二维空数组[[]], 遍历原数组arr,给当前结果res中的每一个子数组append arr[i],得到tempRes[[1]], 再把得到的结果加入到res当中,res变成[[], [1]],以此类推。

function allSubsets(arr){
    let res = [[]];
    for(let i = 0; i < arr.length; i++){
        const tempRes = res.map(subset => {
            const one = subset.concat([]);
            one.push(arr[i]);
            return one;
        })
        res = res.concat(tempRes);
    }
    return res;
}
allSubsets([1,2,3]); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务