Created
November 24, 2024 05:15
-
-
Save sAVItar02/123b942704b2917de2426c0a95d0021a to your computer and use it in GitHub Desktop.
Permutations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums | |
* @return {number[][]} | |
*/ | |
var permute = function(nums, res = [], temp = []) { | |
if(nums.length === 0) res.push([...temp]); | |
for(let i=0; i<nums.length; i++) { | |
// Choose | |
temp.push(nums[i]); | |
let rest = nums.filter((e, index) => index !== i); | |
// Backtrack | |
permute(rest, res, temp); | |
// Unchoose | |
temp.pop(); | |
} | |
return res; | |
}; | |
// Loop through the array and for every element and choose the current element as starting element, either choose it or dont choose it and store it in temp; | |
// once all choices have been made, push temp in results array and repeat for the next element | |
// Time: O(n!) | |
// Space: O(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment