LeetCode: Permutations Solution
Backtracking with chosen stateImplementation
1var permute = function (nums) {2 const n = nums.length3 const chosen = Array(n).fill(false)4 const res = []56 const recursion = (permutation = []) => {7 if (permutation.length === n) {8 res.push([...permutation])9 return10 }1112 for (let i = 0; i < n; i++) {13 if (chosen[i]) continue14 permutation.push(nums[i])15 chosen[i] = true16 recursion(permutation)17 chosen[i] = false18 permutation.pop()19 }20 }2122 recursion()2324 return res25}
References
Similar problems
Next Permutation
Permutations II
Permutation Sequence
Combinations
Comments
Loading comments...
Tags
leetcode
array
backtracking
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.