数据结构与算法--排列(数组全排列)

/**
 * 求数组的全排列
 * @param nums
 * @returns {Array}
 */
function permute(nums) {


  const resPms = [];
  const used = Array(nums.length).fill(false); // 需要对已经参与排列的元素进行记录;但要注意在递归回调结束时要记得回溯

  /**
   * 向这个排列的末尾添加第 index+1 个元素,获得一个有 index + 1 元素的排列
   * @param nums
   * @param index
   * @param p 保存了一个有index个元素的排列
   */
  function generatePermutations(nums, index, p) {
    if (index === nums.length) {
      resPms.push([...p]); // 复制数组
      return;
    }

    for (let i = 0; i < nums.length; i++) {
      if (!used[i]) {
        // 将 nums[i] 添加到p中
        p.push(nums[i]);
        used[i] = true;
        generatePermutations(nums, index + 1, p);
        p.pop();
        used[i]= false;
      }
    }

    return;
  }

  if (nums.length === 0) {
    return resPms;
  }

  const p = [];
  generatePermutations(nums, 0, p);

  return resPms;
}

console.log(permute([1, 2, 3]));

猜你喜欢

转载自blog.csdn.net/u013234372/article/details/82912247