> For the complete documentation index, see [llms.txt](https://akk9132.gitbook.io/seungdeok-log/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://akk9132.gitbook.io/seungdeok-log/knowledge/algorithm/and.md).

# 순열 & 조합

### 순열

> * O(n!)
> * 재귀함수로 구현

```javascript
function permutations(arr, n) {
  if (n === 1) return arr.map((v) => [v]);
  let result = [];

  arr.forEach((fixed, idx, arr) => {
    const rest = arr.filter((_, index) => index !== idx);
    const perms = permutations(rest, n - 1);
    const combine = perms.map((v) => [fixed, ...v]);
    result.push(...combine);
  });

  return result;
}
```

### 조합

> * O(2^n)
> * 재귀함수로 구현

```javascript
function combinations(arr, n) {
  if (n === 1) return arr.map((v) => [v]);
  const result = [];

  arr.forEach((fixed, idx, arr) => {
    const rest = arr.slice(idx + 1);
    const combis = combinations(rest, n - 1);
    const combine = combis.map((v) => [fixed, ...v]);
    result.push(...combine);
  });

  return result;
}

[...new Set(combinations(arr, n)] // 중복제거
```
