Permutations (순열)
If you prefer english, I recommend you to use immersive translation or google translate.
개요
서로 다른 n개의 원소에서 r개를 선택하여 나열하는 경우의 수
재귀
코드
function getPermutations<T>(arr: T[]): T[][] {
const result: T[][] = [];
function permute(currentPermutation: T[], remainingElements: T[]) {
if (remainingElements.length === 0) {
result.push(currentPermutation);
return;
}
for (let i = 0; i < remainingElements.length; i++) {
const nextElement = remainingElements[i];
const newRemainingElements = remainingElements.slice(0, i).concat(remainingElements.slice(i + 1));
permute(currentPermutation.concat(nextElement), newRemainingElements);
}
}
permute([], arr);
return result;
}
기본적인 아이디어는 아래와 같다.
- 남은 요소 중 하나를 선택하여 현재 순열에 추가
- 나머지 요소들로 다시 순열을 생성 (재귀)
- 모든 요소를 선택하면 순열 완성