用js写一个通用全排列函数
时间: 2024-03-12 13:46:14 浏览: 20
以下是一个使用 JavaScript 实现通用全排列函数的示例代码:
```javascript
function permute(arr) {
const result = [];
function backtrack(start) {
if (start === arr.length - 1) {
result.push([...arr]);
return;
}
for (let i = start; i < arr.length; i++) {
[arr[start], arr[i]] = [arr[i], arr[start]];
backtrack(start + 1);
[arr[start], arr[i]] = [arr[i], arr[start]];
}
}
backtrack(0);
return result;
}
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];
const permutations1 = permute(arr1);
console.log(permutations1);
const permutations2 = permute(arr2);
console.log(permutations2);
```
上述代码中,`permute` 函数接收一个数组 `arr`,并返回数组中所有元素的全排列。该函数使用回溯算法实现,其中 `backtrack` 函数用于递归生成所有的排列。在每次递归中,我们从数组中选取一个元素,并将其与 `start` 索引处的元素交换位置。然后,我们递归调用 `backtrack` 函数,将 `start` 索引加一。在递归返回后,我们需要将交换的元素还原到原来的位置。最后,我们返回生成的所有排列。
该函数适用于任意长度和类型的数组,因为它只依赖于数组的索引来生成排列,而不依赖于数组元素的值。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)