mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-25 13:13:04 +08:00
feat(ko): add the Korean online edition (#2006)
* feat(ko): add the complete Korean online edition * Use UTF-8 for Python CI output on Windows * Remove print-book promotion from the Korean site * fix(ko): preserve emphasis before Korean particles
This commit is contained in:
55
ko/codes/javascript/chapter_backtracking/n_queens.js
Normal file
55
ko/codes/javascript/chapter_backtracking/n_queens.js
Normal file
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* File: n_queens.js
|
||||
* Created Time: 2023-05-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* 백트래킹 알고리즘: n-퀸 */
|
||||
function backtrack(row, n, state, res, cols, diags1, diags2) {
|
||||
// 모든 행에 배치했으면 해를 기록한다
|
||||
if (row === n) {
|
||||
res.push(state.map((row) => row.slice()));
|
||||
return;
|
||||
}
|
||||
// 모든 열을 순회한다
|
||||
for (let col = 0; col < n; col++) {
|
||||
// 해당 칸이 속한 주대각선과 부대각선을 계산한다
|
||||
const diag1 = row - col + n - 1;
|
||||
const diag2 = row + col;
|
||||
// 가지치기: 해당 칸이 속한 열, 주대각선, 부대각선에 퀸이 있으면 안 된다
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// 시도: 해당 칸에 퀸을 놓는다
|
||||
state[row][col] = 'Q';
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// 다음 행에 배치한다
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// 되돌리기: 해당 칸을 빈칸으로 되돌린다
|
||||
state[row][col] = '#';
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* n-퀸 문제 풀기 */
|
||||
function nQueens(n) {
|
||||
// n*n 크기의 체스판을 초기화한다. 'Q'는 퀸, '#'은 빈칸을 나타낸다
|
||||
const state = Array.from({ length: n }, () => Array(n).fill('#'));
|
||||
const cols = Array(n).fill(false); // 열에 퀸이 있는지 기록한다
|
||||
const diags1 = Array(2 * n - 1).fill(false); // 주대각선에 퀸이 있는지 기록한다
|
||||
const diags2 = Array(2 * n - 1).fill(false); // 부대각선에 퀸이 있는지 기록한다
|
||||
const res = [];
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
return res;
|
||||
}
|
||||
|
||||
// 실행 코드
|
||||
const n = 4;
|
||||
const res = nQueens(n);
|
||||
|
||||
console.log(`입력한 체스판의 가로와 세로 길이: ${n}`);
|
||||
console.log(`퀸을 배치하는 방법은 총 ${res.length}가지이다`);
|
||||
res.forEach((state) => {
|
||||
console.log('--------------------');
|
||||
state.forEach((row) => console.log(row));
|
||||
});
|
||||
42
ko/codes/javascript/chapter_backtracking/permutations_i.js
Normal file
42
ko/codes/javascript/chapter_backtracking/permutations_i.js
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* File: permutations_i.js
|
||||
* Created Time: 2023-05-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* 백트래킹 알고리즘: 모든 순열 I */
|
||||
function backtrack(state, choices, selected, res) {
|
||||
// 상태의 길이가 원소 개수와 같으면 해를 기록한다
|
||||
if (state.length === choices.length) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// 모든 선택지를 순회한다
|
||||
choices.forEach((choice, i) => {
|
||||
// 가지치기: 원소를 중복하여 선택할 수 없다
|
||||
if (!selected[i]) {
|
||||
// 시도: 선택하고 상태를 갱신한다
|
||||
selected[i] = true;
|
||||
state.push(choice);
|
||||
// 다음 선택을 진행한다
|
||||
backtrack(state, choices, selected, res);
|
||||
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
|
||||
selected[i] = false;
|
||||
state.pop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* 모든 순열 I */
|
||||
function permutationsI(nums) {
|
||||
const res = [];
|
||||
backtrack([], nums, Array(nums.length).fill(false), res);
|
||||
return res;
|
||||
}
|
||||
|
||||
// 실행 코드
|
||||
const nums = [1, 2, 3];
|
||||
const res = permutationsI(nums);
|
||||
|
||||
console.log(`입력 배열 nums = ${JSON.stringify(nums)}`);
|
||||
console.log(`모든 순열 res = ${JSON.stringify(res)}`);
|
||||
44
ko/codes/javascript/chapter_backtracking/permutations_ii.js
Normal file
44
ko/codes/javascript/chapter_backtracking/permutations_ii.js
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* File: permutations_ii.js
|
||||
* Created Time: 2023-05-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* 백트래킹 알고리즘: 모든 순열 II */
|
||||
function backtrack(state, choices, selected, res) {
|
||||
// 상태의 길이가 원소 개수와 같으면 해를 기록한다
|
||||
if (state.length === choices.length) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// 모든 선택지를 순회한다
|
||||
const duplicated = new Set();
|
||||
choices.forEach((choice, i) => {
|
||||
// 가지치기: 원소를 중복하여 선택할 수 없으며, 값이 같은 원소도 중복하여 선택할 수 없다
|
||||
if (!selected[i] && !duplicated.has(choice)) {
|
||||
// 시도: 선택하고 상태를 갱신한다
|
||||
duplicated.add(choice); // 선택한 원소의 값을 기록한다
|
||||
selected[i] = true;
|
||||
state.push(choice);
|
||||
// 다음 선택을 진행한다
|
||||
backtrack(state, choices, selected, res);
|
||||
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
|
||||
selected[i] = false;
|
||||
state.pop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* 모든 순열 II */
|
||||
function permutationsII(nums) {
|
||||
const res = [];
|
||||
backtrack([], nums, Array(nums.length).fill(false), res);
|
||||
return res;
|
||||
}
|
||||
|
||||
// 실행 코드
|
||||
const nums = [1, 2, 2];
|
||||
const res = permutationsII(nums);
|
||||
|
||||
console.log(`입력 배열 nums = ${JSON.stringify(nums)}`);
|
||||
console.log(`모든 순열 res = ${JSON.stringify(res)}`);
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* File: preorder_traversal_i_compact.js
|
||||
* Created Time: 2023-05-09
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* 전위 순회: 예제 1 */
|
||||
function preOrder(root, res) {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
if (root.val === 7) {
|
||||
// 해를 기록한다
|
||||
res.push(root);
|
||||
}
|
||||
preOrder(root.left, res);
|
||||
preOrder(root.right, res);
|
||||
}
|
||||
|
||||
// 실행 코드
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\n이진 트리 초기화');
|
||||
printTree(root);
|
||||
|
||||
// 전위 순회
|
||||
const res = [];
|
||||
preOrder(root, res);
|
||||
|
||||
console.log('\n값이 7인 모든 노드 출력');
|
||||
console.log(res.map((node) => node.val));
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* File: preorder_traversal_ii_compact.js
|
||||
* Created Time: 2023-05-09
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* 전위 순회: 예제 2 */
|
||||
function preOrder(root, path, res) {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
// 시도
|
||||
path.push(root);
|
||||
if (root.val === 7) {
|
||||
// 해를 기록한다
|
||||
res.push([...path]);
|
||||
}
|
||||
preOrder(root.left, path, res);
|
||||
preOrder(root.right, path, res);
|
||||
// 되돌리기
|
||||
path.pop();
|
||||
}
|
||||
|
||||
// 실행 코드
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\n이진 트리 초기화');
|
||||
printTree(root);
|
||||
|
||||
// 전위 순회
|
||||
const path = [];
|
||||
const res = [];
|
||||
preOrder(root, path, res);
|
||||
|
||||
console.log('\n루트 노드에서 노드 7까지의 모든 경로 출력');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_compact.js
|
||||
* Created Time: 2023-05-09
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* 전위 순회: 예제 3 */
|
||||
function preOrder(root, path, res) {
|
||||
// 가지치기
|
||||
if (root === null || root.val === 3) {
|
||||
return;
|
||||
}
|
||||
// 시도
|
||||
path.push(root);
|
||||
if (root.val === 7) {
|
||||
// 해를 기록한다
|
||||
res.push([...path]);
|
||||
}
|
||||
preOrder(root.left, path, res);
|
||||
preOrder(root.right, path, res);
|
||||
// 되돌리기
|
||||
path.pop();
|
||||
}
|
||||
|
||||
// 실행 코드
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\n이진 트리 초기화');
|
||||
printTree(root);
|
||||
|
||||
// 전위 순회
|
||||
const path = [];
|
||||
const res = [];
|
||||
preOrder(root, path, res);
|
||||
|
||||
console.log('\n루트 노드에서 노드 7까지의 모든 경로 출력. 경로에는 값이 3인 노드가 포함되지 않는다');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_template.js
|
||||
* Created Time: 2023-05-09
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
const { arrToTree } = require('../modules/TreeNode');
|
||||
const { printTree } = require('../modules/PrintUtil');
|
||||
|
||||
/* 현재 상태가 해인지 판단 */
|
||||
function isSolution(state) {
|
||||
return state && state[state.length - 1]?.val === 7;
|
||||
}
|
||||
|
||||
/* 해를 기록한다 */
|
||||
function recordSolution(state, res) {
|
||||
res.push([...state]);
|
||||
}
|
||||
|
||||
/* 현재 상태에서 해당 선택이 유효한지 판단 */
|
||||
function isValid(state, choice) {
|
||||
return choice !== null && choice.val !== 3;
|
||||
}
|
||||
|
||||
/* 상태 갱신 */
|
||||
function makeChoice(state, choice) {
|
||||
state.push(choice);
|
||||
}
|
||||
|
||||
/* 상태 복원 */
|
||||
function undoChoice(state) {
|
||||
state.pop();
|
||||
}
|
||||
|
||||
/* 백트래킹 알고리즘: 예제 3 */
|
||||
function backtrack(state, choices, res) {
|
||||
// 해인지 확인한다
|
||||
if (isSolution(state)) {
|
||||
// 해를 기록한다
|
||||
recordSolution(state, res);
|
||||
}
|
||||
// 모든 선택지를 순회한다
|
||||
for (const choice of choices) {
|
||||
// 가지치기: 선택이 유효한지 확인한다
|
||||
if (isValid(state, choice)) {
|
||||
// 시도: 선택하고 상태를 갱신한다
|
||||
makeChoice(state, choice);
|
||||
// 다음 선택을 진행한다
|
||||
backtrack(state, [choice.left, choice.right], res);
|
||||
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
|
||||
undoChoice(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 실행 코드
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\n이진 트리 초기화');
|
||||
printTree(root);
|
||||
|
||||
// 백트래킹 알고리즘
|
||||
const res = [];
|
||||
backtrack([], [root], res);
|
||||
|
||||
console.log('\n값이 3인 노드를 포함하지 않는 조건으로, 루트 노드에서 노드 7까지의 모든 경로 출력');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
46
ko/codes/javascript/chapter_backtracking/subset_sum_i.js
Normal file
46
ko/codes/javascript/chapter_backtracking/subset_sum_i.js
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* File: subset_sum_i.js
|
||||
* Created Time: 2023-07-30
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* 백트래킹 알고리즘: 부분 집합 합 I */
|
||||
function backtrack(state, target, choices, start, res) {
|
||||
// 부분 집합의 합이 target과 같으면 해를 기록한다
|
||||
if (target === 0) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// 모든 선택지를 순회한다
|
||||
// 가지치기 2: start부터 순회하여 중복 부분 집합 생성을 방지한다
|
||||
for (let i = start; i < choices.length; i++) {
|
||||
// 가지치기 1: 부분 집합의 합이 target을 초과하면 즉시 반복문을 종료한다
|
||||
// 배열이 정렬되어 있어 뒤의 원소가 더 크므로, 부분 집합의 합이 반드시 target을 초과하기 때문이다
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// 시도: 선택하고 target, start를 갱신한다
|
||||
state.push(choices[i]);
|
||||
// 다음 선택을 진행한다
|
||||
backtrack(state, target - choices[i], choices, i, res);
|
||||
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* 부분 집합 합 I 풀기 */
|
||||
function subsetSumI(nums, target) {
|
||||
const state = []; // 상태(부분 집합)
|
||||
nums.sort((a, b) => a - b); // nums를 정렬한다
|
||||
const start = 0; // 순회 시작 위치
|
||||
const res = []; // 결과 리스트(부분 집합 리스트)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 실행 코드 */
|
||||
const nums = [3, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumI(nums, target);
|
||||
console.log(`입력 배열 nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`합이 ${target}인 모든 부분 집합 res = ${JSON.stringify(res)}`);
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* File: subset_sum_i_naive.js
|
||||
* Created Time: 2023-07-30
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* 백트래킹 알고리즘: 부분 집합 합 I */
|
||||
function backtrack(state, target, total, choices, res) {
|
||||
// 부분 집합의 합이 target과 같으면 해를 기록한다
|
||||
if (total === target) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// 모든 선택지를 순회한다
|
||||
for (let i = 0; i < choices.length; i++) {
|
||||
// 가지치기: 부분 집합의 합이 target을 초과하면 해당 선택을 건너뛴다
|
||||
if (total + choices[i] > target) {
|
||||
continue;
|
||||
}
|
||||
// 시도: 선택하고 원소의 합 total을 갱신한다
|
||||
state.push(choices[i]);
|
||||
// 다음 선택을 진행한다
|
||||
backtrack(state, target, total + choices[i], choices, res);
|
||||
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* 부분 집합 합 I 풀기(중복 부분 집합 포함) */
|
||||
function subsetSumINaive(nums, target) {
|
||||
const state = []; // 상태(부분 집합)
|
||||
const total = 0; // 부분 집합의 합
|
||||
const res = []; // 결과 리스트(부분 집합 리스트)
|
||||
backtrack(state, target, total, nums, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 실행 코드 */
|
||||
const nums = [3, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumINaive(nums, target);
|
||||
console.log(`입력 배열 nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`합이 ${target}인 모든 부분 집합 res = ${JSON.stringify(res)}`);
|
||||
console.log('이 방법의 출력 결과에는 중복 집합이 포함된다');
|
||||
51
ko/codes/javascript/chapter_backtracking/subset_sum_ii.js
Normal file
51
ko/codes/javascript/chapter_backtracking/subset_sum_ii.js
Normal file
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: subset_sum_ii.js
|
||||
* Created Time: 2023-07-30
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* 백트래킹 알고리즘: 부분 집합 합 II */
|
||||
function backtrack(state, target, choices, start, res) {
|
||||
// 부분 집합의 합이 target과 같으면 해를 기록한다
|
||||
if (target === 0) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// 모든 선택지를 순회한다
|
||||
// 가지치기 2: start부터 순회하여 중복 부분 집합 생성을 방지한다
|
||||
// 가지치기 3: start부터 순회하여 같은 원소의 중복 선택을 방지한다
|
||||
for (let i = start; i < choices.length; i++) {
|
||||
// 가지치기 1: 부분 집합의 합이 target을 초과하면 즉시 반복문을 종료한다
|
||||
// 배열이 정렬되어 있어 뒤의 원소가 더 크므로, 부분 집합의 합이 반드시 target을 초과하기 때문이다
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// 가지치기 4: 해당 원소가 왼쪽 원소와 같으면 탐색 분기가 중복되므로 바로 건너뛴다
|
||||
if (i > start && choices[i] === choices[i - 1]) {
|
||||
continue;
|
||||
}
|
||||
// 시도: 선택하고 target, start를 갱신한다
|
||||
state.push(choices[i]);
|
||||
// 다음 선택을 진행한다
|
||||
backtrack(state, target - choices[i], choices, i + 1, res);
|
||||
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* 부분 집합 합 II 풀기 */
|
||||
function subsetSumII(nums, target) {
|
||||
const state = []; // 상태(부분 집합)
|
||||
nums.sort((a, b) => a - b); // nums를 정렬한다
|
||||
const start = 0; // 순회 시작 위치
|
||||
const res = []; // 결과 리스트(부분 집합 리스트)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* 실행 코드 */
|
||||
const nums = [4, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumII(nums, target);
|
||||
console.log(`입력 배열 nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`합이 ${target}인 모든 부분 집합 res = ${JSON.stringify(res)}`);
|
||||
Reference in New Issue
Block a user