假设,有一个数组为[1,2,3,4,5];再给定一个数字如7,将数组间的值进行加法运算,怎么求出最后结果为[2,5],[3,4],[1,2,4]?</span>
const sumArray = arr => arr.reduce((s, i) => s + i,0)
const newSpliceArray = (arr, index) => {
let newArr = arr.slice(0)
newArr.splice(index, 1)
return newArr
}
const pickArrOfSum = function pickArrOfSum (arr = [], sum, base = [], set = new Set()) {
const currentSum = sumArray(base)
if (currentSum > sum) {
// DO Nothing
} else if (currentSum === sum) {
set.add(base.sort().join(','))
} else {
arr.map((item, index) => {
pickArrOfSum(newSpliceArray(arr, index), sum, base.concat(item), set)
})
}
return set
}
// test
console.log(pickArrOfSum([1, 2, 3, 4, 5], 6))
console.log(pickArrOfSum([1, 2, 3, 4, 5], 7))
console.log(pickArrOfSum([1, 2, 3, 4, 5], 8))
复制到控制台运行即可看到结果