我们有一个数组 ` [5,1,6] `,我们要生成所有的子组合 ` [ [ 5 ], [ 5, 1 ], [ 5, 1, 6 ], [ 5, 6 ], [ 1 ], [ 1, 6 ], [ 6 ] ] `,针对任意数组,该如何求出它的所有子组合呢?
/**
* @param {number[]} nums
* @return {number}
*/
var subset = function (nums) {
let len = nums.length
function bt(start, arr) {
if (start >= len) return []
let subset = []
for (let i = start; i < len; i++) {
let n = nums[i]
let one = [...arr, n]
subset.push(one)
subset.push(...bt(i + 1, one))
}
return subset
}
let subset = bt(0, [])
console.log(subset)
};
第二种解法。
function subset2(nums) {
let len = nums.length
let total = 1 << len
let subset = []
let count = 0
for (let i = 1; i < total; i++) {
let temp = []
for (let j = 0; j < len; j++) {
if ((i >> j) & 1) {
temp.push(nums[j])
}
count++
}
subset.push(temp)
}
console.log(subset, count)
// return subset
}
subset2(['a', 'b', 'c'])
