Skip to content

Commit

Permalink
Merge pull request #42 from algo-malgo/algorithm/#41
Browse files Browse the repository at this point in the history
15649~15650 N과 M (1~2) 다시 풀기
  • Loading branch information
NamJwong authored Sep 12, 2022
2 parents 1be173d + cb7d1b2 commit 32a7412
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 24 deletions.
1 change: 1 addition & 0 deletions BOJ/15649 N과 M (1)/input.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
4 4
27 changes: 27 additions & 0 deletions BOJ/15649 N과 M (1)/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const solution = (N, M) => {
const answer = [];

const visited = Array(N + 1).fill(false);
visited[0] = null;

const dfs = (arr) => {
if (arr.length === M) answer.push(arr);
else {
for (let i = 1; i <= N; i++) {
if (!visited[i]) {
visited[i] = true;
dfs([...arr, i]);
visited[i] = false;
}
}
}
};
dfs([]);
return answer.map((arr) => arr.join(' ')).join('\n');
};

const fs = require('fs');
const file = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
const [N, M] = fs.readFileSync(file).toString().trim().split(' ').map(Number);

console.log(solution(N, M));
45 changes: 21 additions & 24 deletions BOJ/15650 N과 M (2)/main.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,28 @@
const solution = (N, M) => {
const getCombinations = (arr, selectNumber) => {
const results = [];
if (selectNumber === 1) return arr.map((el) => [el]);
arr.forEach((fixed, index, origin) => {
const rest = origin.slice(index + 1);
const combinations = getCombinations(rest, selectNumber - 1);
const attached = combinations.map((el) => [fixed, ...el]);
results.push(...attached);
});
return results;
};
const answer = [];

const visited = Array(N + 1).fill(false);
visited[0] = null;

getCombinations(
Array(N)
.fill(null)
.map((_, idx) => idx + 1),
M
).forEach((c) => console.log(...c));
const dfs = (arr) => {
if (arr.length === M) answer.push(arr);
else {
let i = arr.length ? arr[arr.length - 1] + 1 : 1;
for (; i <= N; i++) {
if (!visited[i]) {
visited[i] = true;
dfs([...arr, i]);
visited[i] = false;
}
}
}
};
dfs([]);
return answer.map((arr) => arr.join(' ')).join('\n');
};

const fs = require('fs');
const file = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
const [N, M] = fs
.readFileSync(file)
.toString()
.trim()
.split(' ')
.map((c) => +c);
const [N, M] = fs.readFileSync(file).toString().trim().split(' ').map(Number);

solution(N, M);
console.log(solution(N, M));

0 comments on commit 32a7412

Please sign in to comment.