阵列排列如何通过(n)分裂
所以我有数组,
const arr = [ 1, 4, 5, 8]
我想获得(n)数字拆分的该数组的所有可能组合 例如,
function getNPermutate(arr, n) {
}
getNPermutate(arr, 3) // [[1, 4, 5], [1, 4, 8], [4, 5, 8],[1, 5 ,8] ]
!array可以是任何长度
我找到了简单排列的解决方案,但不明白置换置换的方式
function permute(nums) {
let result = [];
if (nums.length === 0) return [];
if (nums.length === 1) return [nums];
for (let i = 0; i < nums.length; i++) {
const currentNum = nums[i];
const remainingNums = nums.slice(0, i).concat(nums.slice(i + 1));
const remainingNumsPermuted = permute(remainingNums);
for (let j = 0; j < remainingNumsPermuted.length; j++) {
const permutedArray = [currentNum].concat(remainingNumsPermuted[j]);
result.push(permutedArray);
}
}
return result;
}
console.log(permute([1,2,3,4]))
So I have array
const arr = [ 1, 4, 5, 8]
I want to get all possible combinations of this array splitted by (n) number
for example
function getNPermutate(arr, n) {
}
getNPermutate(arr, 3) // [[1, 4, 5], [1, 4, 8], [4, 5, 8],[1, 5 ,8] ]
!array can be any length
I found the solution with simple permutation, but dont understand how do splitted permutation
function permute(nums) {
let result = [];
if (nums.length === 0) return [];
if (nums.length === 1) return [nums];
for (let i = 0; i < nums.length; i++) {
const currentNum = nums[i];
const remainingNums = nums.slice(0, i).concat(nums.slice(i + 1));
const remainingNumsPermuted = permute(remainingNums);
for (let j = 0; j < remainingNumsPermuted.length; j++) {
const permutedArray = [currentNum].concat(remainingNumsPermuted[j]);
result.push(permutedArray);
}
}
return result;
}
console.log(permute([1,2,3,4]))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试此一个:
脚本:
输出:
You can try this one:
Script:
Output:
您可以使用递归发电机:
要将发电机转换为返回嵌套数组的普通函数,请执行:
You could use a recursive generator:
To convert the generator to a normal function that returns a nested array, do: