Open Pcjmy opened 1 year ago
/**
* Generates all possible permutations of the given array.
* 找好截止条件
* 都可以抽象为树的深度遍历,只是遍历的过程中要剪枝
*
* @param {number[]} nums - The array of numbers to permute.
* @return {number[][]} - An array containing all possible permutations of the input array.
*/
var permute = function(nums) {
const res = [];
const dfs = (numList, temp) => {
if(temp.length === nums.length) {
res.push(temp.slice()); // temp是引用类型
return;
}
for(let value of numList) {
if (temp.includes(value)) continue; // 确保元素不重复
temp.push(value);
dfs(numList, temp);
temp.pop();
}
}
dfs(nums, [])
return res;
};
const arr = ["a","b","c","d","e"];
console.log(permute(arr))
非递归方法
function main(arr) {
if (!arr.length) return []
let res = [arr[0]]
for (let i = 1; i < arr.length; i++) {
let temp = []
for (const item of res) {
for (let x = 0; x <= item.length; x++) {
temp.push(item.slice(0, x) + arr[i] + item.slice(x))
}
}
res = temp
}
return res
}