다음을 수행하는 함수를 작성해야 합니다. -
-
정수 배열을 인수로 취합니다(예:[1,2,3,4])
-
[1,2,3,4]의 가능한 모든 순열 배열을 생성하며 각 순열은 길이가 4(즉, 원래 배열의 길이)입니다.
예시
이에 대한 코드는 -
const arr = [1, 2, 3, 4];
const permute = (arr = [], res = [], used = []) => {
let i, ch;
for (i = 0; i < arr.length; i++) {
ch = arr.splice(i, 1)[0];
used.push(ch);
if (arr.length === 0) {
res.push(used.slice());
}
permute(arr, res, used);
arr.splice(i, 0, ch);
used.pop();
};
return res;
};
console.log(permute(arr)); 출력
콘솔의 출력은 -
[ [ 1, 2, 3, 4 ], [ 1, 2, 4, 3 ], [ 1, 3, 2, 4 ], [ 1, 3, 4, 2 ], [ 1, 4, 2, 3 ], [ 1, 4, 3, 2 ], [ 2, 1, 3, 4 ], [ 2, 1, 4, 3 ], [ 2, 3, 1, 4 ], [ 2, 3, 4, 1 ], [ 2, 4, 1, 3 ], [ 2, 4, 3, 1 ], [ 3, 1, 2, 4 ], [ 3, 1, 4, 2 ], [ 3, 2, 1, 4 ], [ 3, 2, 4, 1 ], [ 3, 4, 1, 2 ], [ 3, 4, 2, 1 ], [ 4, 1, 2, 3 ], [ 4, 1, 3, 2 ], [ 4, 2, 1, 3 ], [ 4, 2, 3, 1 ], [ 4, 3, 1, 2 ], [ 4, 3, 2, 1 ] ]