-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBOJ15650.js
77 lines (60 loc) · 1.66 KB
/
BOJ15650.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Solution 1
function getCombinations(array, selectNumber) {
const results = [];
if (selectNumber === 1) {
return array.map((item) => [item]);
}
array.forEach((fixed, index, origin) => {
const rest = origin.slice(index + 1);
const combinations = getCombinations(rest, selectNumber - 1);
const attached = combinations.map((combination) => [fixed, ...combination]);
results.push(...attached);
});
return results;
}
function solution1(n, m) {
const array = Array.from({ length: n }, (_, index) => index + 1);
const combinations = getCombinations(array, m);
let result = '';
for (const combination of combinations) {
result += combination.join(' ') + '\n';
}
return result;
}
// Solution 2
function getCombinations(array, selectNumber) {
const combinations = [];
const combination = Array.from({ length: selectNumber }, () => 0);
function dfs(l, start) {
if (l === selectNumber) {
combinations.push(combination.slice());
} else {
for (let i = start; i < array.length; i++) {
combination[l] = array[i];
dfs(l + 1, i + 1);
}
}
}
dfs(0, 0);
return combinations;
}
function solution2(n, m) {
const array = Array.from({ length: n }, (_, index) => index + 1);
const combinations = getCombinations(array, m);
let result = '';
for (const combination of combinations) {
result += combination.join(' ') + '\n';
}
return result;
}
const fs = require('fs');
const input = fs
.readFileSync('/dev/stdin')
.toString()
.trim()
.split(' ')
.map((value) => parseInt(value));
const n = input[0];
const m = input[1];
console.log(solution1(n, m));
console.log(solution2(n, m));