-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination.js
More file actions
36 lines (30 loc) · 803 Bytes
/
combination.js
File metadata and controls
36 lines (30 loc) · 803 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
items: 선택한 요소를 담는 배열
idx: list의 인덱스
k: list 중에서 선택하는 개수
**/
function combination(items, idx, list, k, result) {
if (items.length === k) {
result.push(items);
return;
}
for (let i = idx; i < list.length; i++) {
combination([...items, list[i]], i + 1, list, k, result);
}
}
function combinationWithRepetition(items, idx, list, k, result) {
if (items.length === k) {
result.push(items);
return;
}
for (let i = idx; i < list.length; i++) {
combinationWithRepetition([...items, list[i]], i, list, k, result);
}
}
const list = [1, 2, 3, 4];
let result1 = [];
combination([], 0, list, 2, result1);
console.log(result1);
let result2 = [];
combinationWithRepetition([], 0, list, 2, result2);
console.log(result2);