说我有数组:
[1, 2, 2, 3]
如何获得此数组的所有可能的唯一“拆分”,即:
[[1], [2, 2, 3]]
[[1], [2, 2], [3]]
[[1], [2, 3], [2]]
[[1], [2], [2], [3]]
[[1, 2], [2, 3]]
[[1, 2], [2], [3]]
[[1, 3], [2, 2]]
[[1, 3], [2], [2]]
[[1, 2, 2], [3]]
[[1, 2, 3], [2]]
[[1, 2, 2, 3]]
请注意,组合或组合内的顺序都不重要。即这些本质上是“多集”]
根据您的示例数组,只有15种组合。要获得所有可能的组合,可以使用此功能。
function subset(array){
var subsets = [], tempArray;
//loop throug possible combinations
for(var x = 1; x <= (Math.pow(2, array.length) - 1); x++) {
tempArray = [];
i = array.length;
//loop through array
do {
//using bitwise operator
//eg: x = 1, i = 1, condtion true store value
if((x & (1 << i)) !== 0) {
tempArray.push(array[i]);
}
} while(i--);
subsets.push(tempArray);
}
return subsets;
}
console.log(subset([1, 2]));
console.log(subset([1, 2, 2, 3]));