我有数组[1,2,3,4]
我想打印所有组合,如:
[1]
[2]
[3]
[4]
[1,2]
[1,2,3]
[1,2,3,4]
[2,3]
[2,3,4]
[3,4]
[1,3]
[1,3,4]
[1,4]
[2,4]
我怎么能这样做?
答案 0 :(得分:1)
这很容易递归:
function printCombinations(arr, prefix) {
if (arr.length == 0) {
if (prefix.length > 0) {
console.log(prefix);
}
return;
}
prefix = prefix || [];
printCombinations(arr.slice(1), prefix.concat(arr[0]));
printCombinations(arr.slice(1), prefix);
}
printCombinations([1, 2, 3, 4]);