Source: https://leetcode.com/problems/permutations/
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
/*** @param {number[]} nums* @return {number[][]}*/// O(N!) time for permutations, O(N) space for used arrayvar permute = function(nums) {// Perform DFS on the state-space of possible numbers to form permutationsconst dfs = (path, used, result) => {// Once we've used up all the numbers, we've reached a permutation// Add copy of path to result and returnif (path.length === nums.length) {result.push([...path]);return;}// Loop through each num in numsfor (let i = 0; i < nums.length; i++) {// If the current num is already used, skipif (used[i] === true) {continue;}// Current num is not used, add it to path and set it to usedpath.push(nums[i]);used[i] = true;// Recursively form the rest of the permutationdfs(path, used, result);// We backtrack and pop the used number from path and set used to falsepath.pop();used[i] = false;}};// Initialize used array of length nums with all false for unusedconst used = Array.from({ length: nums.length }, () => false);// Initialize result array to keep track of all the permutationsconst result = [];dfs([], used, result);return result;};