describe
Given a sequence without repeating digits, return all possible permutations.
The sample
Input:1.2.3] Output: [[1.2.3],
[1.3.2],
[2.1.3],
[2.3.1],
[3.1.2],
[3.2.1]]Copy the code
thought
For example, think of the recursion that DFS uses
Recursion requires a boundary, and the boundary here is access to the last pit
Mark the visited object with a Visited object
code
function perOrder(nums){
const length = nums.length
const res = []
const curArr = []
const visited = {}
function dfs(nth) {
if(nth >= length) {
res.push(curArr.slice())
return
}
for(let i = 0; i < length; i++) {
if(! visited[nums[i]]) { curArr.push(nums[i]) visited[nums[i]] =true
dfs(nth + 1)
curArr.pop()
visited[nums[i]] = false
}
}
}
dfs(0)
return res
}
Copy the code