Faaez Razeen

Permutations

  • 3 min read
  • Ae-medium
  • LC-Medium
  • Algoexpert

3 years ago

https://www.algoexpert.io/questions/permutations

Solution

TimeSpaceExplanation
O(n * n!)O(n)See below
def permute(self, nums: List[int]) -> List[List[int]]: ans = [] self.backtrack([], nums, ans) return ans def backtrack(self, curr, nums, ans): if len(curr) == len(nums): ans.append(curr[:]) return for num in nums: if num not in curr: curr.append(num) self.backtrack(curr, nums, ans) curr.pop()

Super Small Solution

def permute(self, nums: List[int]) -> List[List[int]]: ans = [] def backtrack(curr): if len(curr) == len(nums): ans.append(curr) return for num in nums: if num not in curr: backtrack(curr + [num]) backtrack([]) return ans

Alternate Logic (BETTER?)

function permute(nums: number[]): number[][] { let perms = [[]]; // Start with a list containing an empty permutation for (let num of nums) { // Iterate through each number in the input array const newPerms = []; // Initialize a new list for permutations with the current number added for (let perm of perms) { // Iterate through existing permutations for (let i = 0; i <= perm.length; i++) { // Iterate through all possible insertion positions const permCopy = [...perm]; // Create a copy of the current permutation permCopy.splice(i, 0, num); // Insert the current number at position i newPerms.push(permCopy); // Add the new permutation to newPerms } } perms = newPerms; // Update the list of permutations for the next iteration } return perms; };