LeetCode 46. Permutations (javascript solution)

Description:

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Solution:

Time Complexity : O(n!)
Space Complexity: O(n)

var permute = function(choices, temp…


This content originally appeared on DEV Community and was authored by codingpineapple

Description:

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Solution:

Time Complexity : O(n!)
Space Complexity: O(n)

var permute = function(choices, temp = [], permutations = []) {
    // Base case 
    if(choices.length === 0){
      permutations.push([...temp]);
    } 

    for(let i = 0; i < choices.length; i++){
        // Create new array without current letter
        let newChoices = choices.filter((choice, index) => index !== i)
        // Add current to the temp array which is our current permutation
        temp.push(choices[i])
        permute(newChoices, temp, permutations)
        // Once we have explored options remove the current letter from our current permuataion
        temp.pop()
    }

    return permutations
};


This content originally appeared on DEV Community and was authored by codingpineapple


Print Share Comment Cite Upload Translate Updates
APA

codingpineapple | Sciencx (2021-04-26T01:56:17+00:00) LeetCode 46. Permutations (javascript solution). Retrieved from https://www.scien.cx/2021/04/26/leetcode-46-permutations-javascript-solution/

MLA
" » LeetCode 46. Permutations (javascript solution)." codingpineapple | Sciencx - Monday April 26, 2021, https://www.scien.cx/2021/04/26/leetcode-46-permutations-javascript-solution/
HARVARD
codingpineapple | Sciencx Monday April 26, 2021 » LeetCode 46. Permutations (javascript solution)., viewed ,<https://www.scien.cx/2021/04/26/leetcode-46-permutations-javascript-solution/>
VANCOUVER
codingpineapple | Sciencx - » LeetCode 46. Permutations (javascript solution). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/26/leetcode-46-permutations-javascript-solution/
CHICAGO
" » LeetCode 46. Permutations (javascript solution)." codingpineapple | Sciencx - Accessed . https://www.scien.cx/2021/04/26/leetcode-46-permutations-javascript-solution/
IEEE
" » LeetCode 46. Permutations (javascript solution)." codingpineapple | Sciencx [Online]. Available: https://www.scien.cx/2021/04/26/leetcode-46-permutations-javascript-solution/. [Accessed: ]
rf:citation
» LeetCode 46. Permutations (javascript solution) | codingpineapple | Sciencx | https://www.scien.cx/2021/04/26/leetcode-46-permutations-javascript-solution/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.