[Algorithm] Permutations

Write a function that takes in an array of unique integers and returns an array of all permutations of those integers in no particular order.

If the input array is empty, the function should return an empty array.

Sample Input

array = [1, 2, 3]

Sample Output

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

 

when array is empty at the end []
which is our edge case
 
// T: O(N! * N *N)
// S: O(N! * N)
// array filter or array concat is O(N)
function getPermutations(array) {
  const perms = [];
  helper(array, [], perms)
  return perms
}

function helper (array, perm = [], perms = []) {
  // T: O(N!)
  if (!array.length && perm.length !== 0) {
    perms.push(perm)
  } else {
    //O(N * N)
    for (let i = 0; i < array.length; i++) {
      const newArray = array.filter((_, idx) => idx !== i); // don't mutate the array T: O(N)
      const newPerm = [...perm, array[i]]; // don't mutate the perm array T: O(N)
      helper(
        newArray,
        newPerm,
        perms
      )
    }
  }
}

// Do not edit the line below.
exports.getPermutations = getPermutations;

 

// Idea modify array in place
  // 1. swap to get new
  // 2. swap back for next iteration
// S: O (N!* N)
// T: O(N! * N)
// swap will be O(1)
function getPermutations(array) {
  const perms = []
  helper(0, array, perms)
  return perms
}

function helper(i, array, perms) {
  if (i === array.length - 1) {
    perms.push([...array])
  } else {
    for (let j = i; j < array.length; j++) {
      swap(array, i ,j);
      helper(i + 1, array, perms)
      swap(array, i, j);
    }
  }
  
}

function swap(array, i, j) {
  const temp = array[i];
  array[i] = array[j];
  array[j] = temp;
}

// Do not edit the line below.
exports.getPermutations = getPermutations;

posted @   Zhentiw  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-09-15 [CSS3] Use CSS Variables to Maintain the Aspect Ratio for an Element
2020-09-15 [GraphQL] Multi Query and Alias
2020-09-15 [Machine Learning] Gradient Checking
2019-09-15 [ARIA] What is Accessible Name Calculation?
2019-09-15 [ARIA] Accessible animations with reduced motion
2019-09-15 [ARIA] Accessible modal dialogs
2018-09-15 [Tools] Scroll, Zoom, and Highlight code in a mdx-deck slide presentation with Code Surfer <🏄/>
点击右上角即可分享
微信分享提示