SOURCE

/*
 * @Description: 
 * @Author: zhenglong
 * @Date: 2022-08-01 15:28:48
 */
class Permutation {
  constructor(arr) {
    this.arr = Array.from(arr)
    this.result = []
    this.len = 0
    this.run(0)
  }

  run(index) {
    if (index == this.arr.length - 1) {
      this.result.push(Array.from(this.arr))
      this.len++
      return
    }
    for (let i = index; i < this.arr.length; i++) {
      ;[this.arr[index], this.arr[i]] = [this.arr[i], this.arr[index]]

      this.run(index + 1)

        ;[this.arr[index], this.arr[i]] = [this.arr[i], this.arr[index]]   //回溯
    }
  }
}

//i = 0  A  B  C  (index ==0循环)

//A  做头

// index = 1    i =1  i = 2      index+1 ==2   =>    A B C  A C B

//i  = 1   B A C  (index ==0循环)

//B 做头  

// index = 1      i = 1  i = 2    index+1 ==2   =>  B A C   B C A


//i  = 2   C B A  (index ==0循环)

//C 做头 

// index = 1      i = 1  i = 2    index+1 ==2   =>  C B A   C A B





// let p = new Permutation(['A', 'B', 'C'])
// console.log(p.result)
// console.log(p.len)

let result =[]

const arrange = (array, index = 0) => {
    
  let arr = Array.from(array);
 
  if (index == arr.length - 1) {
    result.push(arr);
  }

  for (let i = index; i < arr.length; i++) {
    [arr[i], arr[index]] = [arr[index], arr[i]];

    arrange(arr, index + 1);
   
    [arr[i], arr[index]] = [arr[index], arr[i]];   //回溯(返回原来数组)
  }

   return result
}




let a = arrange([1,2,3])


console.log(a,a.length)
console 命令行工具 X clear

                    
>
console