LeetCode: Permutations Solution

Backtracking with chosen state

Implementation

1var permute = function (nums) {
2 const n = nums.length
3 const chosen = Array(n).fill(false)
4 const res = []
5
6 const recursion = (permutation = []) => {
7 if (permutation.length === n) {
8 res.push([...permutation])
9 return
10 }
11
12 for (let i = 0; i < n; i++) {
13 if (chosen[i]) continue
14 permutation.push(nums[i])
15 chosen[i] = true
16 recursion(permutation)
17 chosen[i] = false
18 permutation.pop()
19 }
20 }
21
22 recursion()
23
24 return res
25}

References

Original problem

Similar problems

Next Permutation

Permutations II

Permutation Sequence

Combinations

Comments

Loading comments...

Tags

leetcode

array

backtracking

Next Post

LeetCode: House Robber

Memoized recusion

Previous Post

LeetCode: Combinations

"Don't try" - Charles Bukowski

HoningJS

Search Posts