Created
December 10, 2021 01:11
-
-
Save nicolekc/5c95a8b77c119090531c247933d9d0e0 to your computer and use it in GitHub Desktop.
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
/** | |
* Input: 1, 2, 3, 4 | |
* Output: | |
* 1 | |
* 1, 2 | |
* 1, 2, 3 | |
* 1, 2, 3, 4 | |
* 1, 2, 4 | |
* 1, 3 | |
* 1, 3, 4 | |
* 1, 4 | |
*/ | |
function permutations(input, index = 0, prefix = [], stack = []) { | |
let next = [ ...prefix, input[index] ]; | |
stack.push(next); | |
for (let i = index + 1; i < input.length; i++) { | |
permutations(input, i, next, stack); | |
} | |
return stack; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment