JavaScript 中的幂集发现集合的幂集
集合 S 的幂集是 S 的所有子集(包括空集和 S 自身)的集合。集合 S 的幂集用 P(S) 表示。
例如
如果 S = {x, y, z},则子集为 -
{
{},
{x},
{y},
{z},
{x, y},
{x, z},
{y, z},
{x, y, z}
}我们需要编写一个 JavaScript 函数,该函数以数组作为唯一参数。该函数应该查找并返回输入数组的幂集。
示例
以下是代码 -
const set = ['x', 'y', 'z'];
const powerSet = (arr = []) => {
const res = [];
const { length } = arr;
const numberOfCombinations = 2 ** length;
for (let combinationIndex = 0; combinationIndex < numberOfCombinations; combinationIndex += 1) {
const subSet = [];
for (let setElementIndex = 0; setElementIndex < arr.length;
setElementIndex += 1) {
if (combinationIndex & (1 << setElementIndex)) {
subSet.push(arr[setElementIndex]);
};
};
res.push(subSet);
};
return res;
};
console.log(powerSet(set));输出
以下是控制台上的输出 -
[ [], [ 'x' ], [ 'y' ], [ 'x', 'y' ], [ 'z' ], [ 'x', 'z' ], [ 'y', 'z' ], [ 'x', 'y', 'z' ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP