如何优化这个递归算法?

原帖 集合的划分
我需要把所有的可能都列出来。。

我根据上面的算法写的代码,但会让浏览器内存爆了,请问如何优化这个递归算法?

大神可以忽略我的代码,直接写自己的代码,解决我的需求。。多谢。

https://img.mukewang.com/5c6fa8420001e88104510923.jpg

蓝山帝景
浏览 647回答 2
2回答

精慕HU

感觉这个就可以一定程度的优化。Js通过记忆优化递归

HUH函数

function group(total, size) {&nbsp; var groupList = []&nbsp; var arr = []&nbsp; for (let i = 0; i < total; i++) {&nbsp; &nbsp; arr.push(i + 1)&nbsp; }&nbsp; (function (arr, size, group) {&nbsp; &nbsp; var arrLen = arr.length&nbsp; &nbsp; if (size > arrLen) return&nbsp; &nbsp; if (size == arrLen) {&nbsp; &nbsp; &nbsp; groupList.push([].concat(group, arr))&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; for (var i = 0; i < arrLen; i++) {&nbsp; &nbsp; &nbsp; &nbsp; var newGroup = [].concat(group)&nbsp; &nbsp; &nbsp; &nbsp; newGroup.push(arr[i])&nbsp; &nbsp; &nbsp; &nbsp; if (size == 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; groupList.push(newGroup)&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var newArr = [].concat(arr)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; newArr.splice(0, i + 1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arguments.callee(newArr, size - 1, newGroup)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; })(arr, size, []);&nbsp; return groupList;}console.log(group(3, 2))console.log(group(4, 2))console.log(group(4, 3))console.log(group(5, 2))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript