Shu-How Zの小窝

Loading...

LeetCode:46.全排列

LeetCode:46.全排列

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function (nums) {
  let res = [];
  let compose = (path) => {
    if (path.length === nums.length) {
      res.push(path);
      return;
    }
    for (let i = 0; i < nums.length; i++) {
      if (!path.includes(nums[i])) {
        compose(path.concat(nums[i]));
      }
    }
  };
  compose([]);
  return res;
};
let nums = [1, 2, 3];
console.log(permute(nums));

解题步骤用递归模拟出所有情况。遇到包含重复元素的情况,就回溯。收集所有到达递归终点的情况,并返回。

时间复杂度:O(n!),n!=1×2×3×..×(n-1)×n空间复杂度:O(n)

'

posted @ 2025-01-19 19:26  KooTeam  阅读(10)  评论(0)    收藏  举报