Created
January 7, 2021 11:05
-
-
Save corocoto/bfd3d51e1c652cd3c9df38f1f92d639f to your computer and use it in GitHub Desktop.
The solution of the task https://leetcode.com/problems/permutations/ by using Heap's Algorithm
This file contains hidden or 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
| /** | |
| * Link on the task: https://leetcode.com/problems/permutations/ | |
| * Description: Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. | |
| * Example: | |
| * Input: nums = [1,2,3] | |
| * Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] | |
| */ | |
| const permute = function(nums) { | |
| return (function permutationHeap(array, n, res = []) { | |
| n = n || array.length; | |
| if (n === 1) { | |
| res.push([...array]) | |
| } else { | |
| for (let i = 1; i <= n; i++) { | |
| permutationHeap(array, n - 1, res); | |
| if (n % 2) { | |
| [array[0], array[n - 1]] = [array[n - 1], array[0]]; | |
| } else { | |
| [array[i - 1], array[n - 1]] = [array[n - 1], array[i - 1]]; | |
| } | |
| } | |
| } | |
| return res; | |
| })(nums); | |
| }; | |
| console.log(permute(["a", "b", "c"])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment