全排列

回溯算法

const fullPermutationByForEach = (nums = [1, 2, 3]) => {
  const res = [];
  const backTrack = (path) => {
    if (path.length === nums.length) {
      res.push(path);
      return;
    }
    for (let i = 0; i < nums.length; i++) {
      const num = nums[i];
      if (path.includes(num)) {
        continue;
      }
      /**
       * path.push(item)
       * backTrack(path)
       * 错误代码:使用push会改变path原数组 所以使用concat生成新数组 入参backTrack方法
       */
      backTrack(path.concat(num));
    }
  };
  backTrack([]);
  return res;
};

  

  

posted @ 2023-01-28 23:10  671_MrSix  阅读(2)  评论(0编辑  收藏  举报