题目
https://leetcode-cn.com/problems/permutations/
思路
- dfs + 回溯
- bfs + 队列
code
var permute = function (nums) {
// dfs
// let depth = 0;
// let tags = new Array(nums.length).fill(false);
// let res, tmp;
// res = [];
// tmp = [];
// dfs(nums, depth, tags, res, tmp);
// return res;
// bfs
return bfs(nums, []);
};
var dfs = function (nums, depth, tags, res, tmp) {
if (depth == nums.length) {
res.push([...tmp]);
// 注意这里,不能直接push(tmp),因为我们操作的tmp是同一块内存地址
return;
}
for (let i = 0; i < nums.length; i++) {
if (tags[i] == false) {
tmp.push(nums[i]);
tags[i] = true;
dfs(nums, depth + 1, tags, res, tmp);
tmp.pop();
tags[i] = false;
}
}
}
var bfs = function (nums, res) {
let queue = [];
nums.forEach((item) => {
queue.push([item]);
})
while (queue.length != 0) {
let tmp = queue.shift();
if (tmp.length == nums.length){
res.push(tmp);
continue;
}
for (let i = 0; i < nums.length; i++) {
if (!tmp.includes(nums[i])) {
queue.push([...tmp, nums[i]]);
}
}
}
return res;
}
// console.log(permute([1,2,3]));
总结
- 注意传参的问题,传的是引用
- 数组方法:push,includes,forEach,push,pop,shift