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:
Yudong Jin
2026-10-29 03:46:43 +08:00
committed by GitHub
parent 71a773df64
commit 2f561d3d51
2072 changed files with 110884 additions and 102 deletions

1
ko/codes/java/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
build

View File

@@ -0,0 +1,105 @@
/**
* File: array.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_array_and_linkedlist;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class array {
/* 원소에 임의 접근 */
static int randomAccess(int[] nums) {
// 구간 [0, nums.length)에서 숫자 하나를 무작위로 뽑는다
int randomIndex = ThreadLocalRandom.current().nextInt(0, nums.length);
// 무작위 원소를 가져와 반환한다
int randomNum = nums[randomIndex];
return randomNum;
}
/* 배열 길이 확장 */
static int[] extend(int[] nums, int enlarge) {
// 길이를 확장한 배열을 초기화한다
int[] res = new int[nums.length + enlarge];
// 원래 배열의 모든 원소를 새 배열에 복사한다
for (int i = 0; i < nums.length; i++) {
res[i] = nums[i];
}
// 확장한 새 배열을 반환한다
return res;
}
/* 배열의 인덱스 index에 원소 num 삽입 */
static void insert(int[] nums, int num, int index) {
// 인덱스 index와 그 뒤에 있는 모든 원소를 한 칸씩 뒤로 이동한다
for (int i = nums.length - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// index 위치의 원소에 num을 대입한다
nums[index] = num;
}
/* 인덱스 index에 있는 원소 삭제 */
static void remove(int[] nums, int index) {
// 인덱스 index 뒤에 있는 모든 원소를 한 칸씩 앞으로 이동한다
for (int i = index; i < nums.length - 1; i++) {
nums[i] = nums[i + 1];
}
}
/* 배열 순회 */
static void traverse(int[] nums) {
int count = 0;
// 인덱스를 통해 배열을 순회한다
for (int i = 0; i < nums.length; i++) {
count += nums[i];
}
// 배열의 원소를 직접 순회한다
for (int num : nums) {
count += num;
}
}
/* 배열에서 지정한 원소 탐색 */
static int find(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target)
return i;
}
return -1;
}
/* 실행 코드 */
public static void main(String[] args) {
/* 배열 초기화 */
int[] arr = new int[5];
System.out.println("배열 arr = " + Arrays.toString(arr));
int[] nums = { 1, 3, 2, 5, 4 };
System.out.println("배열 nums = " + Arrays.toString(nums));
/* 임의 접근 */
int randomNum = randomAccess(nums);
System.out.println("nums에서 무작위로 가져온 원소 " + randomNum);
/* 길이 확장 */
nums = extend(nums, 3);
System.out.println("배열 길이를 8로 확장한 후 nums = " + Arrays.toString(nums));
/* 원소 삽입 */
insert(nums, 6, 3);
System.out.println("인덱스 3에 숫자 6을 삽입한 후 nums = " + Arrays.toString(nums));
/* 원소 삭제 */
remove(nums, 2);
System.out.println("인덱스 2의 원소를 삭제한 후 nums = " + Arrays.toString(nums));
/* 배열 순회 */
traverse(nums);
/* 원소 탐색 */
int index = find(nums, 3);
System.out.println("nums에서 원소 3을 탐색하여 얻은 인덱스 = " + index);
}
}

View File

@@ -0,0 +1,86 @@
/**
* File: linked_list.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_array_and_linkedlist;
import utils.*;
public class linked_list {
/* 연결 리스트의 노드 n0 뒤에 노드 P 삽입 */
static void insert(ListNode n0, ListNode P) {
ListNode n1 = n0.next;
P.next = n1;
n0.next = P;
}
/* 연결 리스트의 노드 n0 바로 뒤에 있는 노드 삭제 */
static void remove(ListNode n0) {
if (n0.next == null)
return;
// n0 -> P -> n1
ListNode P = n0.next;
ListNode n1 = P.next;
n0.next = n1;
}
/* 연결 리스트에서 인덱스가 index인 노드에 접근 */
static ListNode access(ListNode head, int index) {
for (int i = 0; i < index; i++) {
if (head == null)
return null;
head = head.next;
}
return head;
}
/* 연결 리스트에서 값이 target인 첫 번째 노드 탐색 */
static int find(ListNode head, int target) {
int index = 0;
while (head != null) {
if (head.val == target)
return index;
head = head.next;
index++;
}
return -1;
}
/* 실행 코드 */
public static void main(String[] args) {
/* 연결 리스트 초기화 */
// 각 노드를 초기화한다
ListNode n0 = new ListNode(1);
ListNode n1 = new ListNode(3);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(5);
ListNode n4 = new ListNode(4);
// 노드 사이의 참조를 설정한다
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
System.out.println("초기화한 연결 리스트");
PrintUtil.printLinkedList(n0);
/* 노드 삽입 */
insert(n0, new ListNode(0));
System.out.println("노드를 삽입한 후의 연결 리스트");
PrintUtil.printLinkedList(n0);
/* 노드 삭제 */
remove(n0);
System.out.println("노드를 삭제한 후의 연결 리스트");
PrintUtil.printLinkedList(n0);
/* 노드 접근 */
ListNode node = access(n0, 3);
System.out.println("연결 리스트에서 인덱스 3에 있는 노드의 값 = " + node.val);
/* 노드 탐색 */
int index = find(n0, 2);
System.out.println("연결 리스트에서 값이 2인 노드의 인덱스 = " + index);
}
}

View File

@@ -0,0 +1,66 @@
/**
* File: list.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_array_and_linkedlist;
import java.util.*;
public class list {
public static void main(String[] args) {
/* 리스트 초기화 */
// 배열의 원소 형식에는 int[]의 래퍼 형식인 Integer[]를 사용한다는 점에 주의한다
Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 };
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
System.out.println("리스트 nums = " + nums);
/* 원소 접근 */
int num = nums.get(1);
System.out.println("인덱스 1의 원소에 접근하여 얻은 num = " + num);
/* 원소 갱신 */
nums.set(1, 0);
System.out.println("인덱스 1의 원소를 0으로 갱신한 후 nums = " + nums);
/* 리스트 비우기 */
nums.clear();
System.out.println("리스트를 비운 후 nums = " + nums);
/* 맨 뒤에 원소 추가 */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
System.out.println("원소를 추가한 후 nums = " + nums);
/* 중간에 원소 삽입 */
nums.add(3, 6);
System.out.println("인덱스 3에 숫자 6을 삽입한 후 nums = " + nums);
/* 원소 삭제 */
nums.remove(3);
System.out.println("인덱스 3의 원소를 삭제한 후 nums = " + nums);
/* 인덱스를 통해 리스트를 순회한다 */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums.get(i);
}
/* 리스트의 원소를 직접 순회한다 */
for (int x : nums) {
count += x;
}
/* 두 리스트 연결 */
List<Integer> nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 }));
nums.addAll(nums1);
System.out.println("리스트 nums1을 nums 뒤에 연결한 후 nums = " + nums);
/* 리스트 정렬 */
Collections.sort(nums);
System.out.println("리스트를 정렬한 후 nums = " + nums);
}
}

View File

@@ -0,0 +1,147 @@
/**
* File: my_list.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_array_and_linkedlist;
import java.util.*;
/* 리스트 클래스 */
class MyList {
private int[] arr; // 배열(리스트 원소 저장)
private int capacity = 10; // 리스트 용량
private int size = 0; // 리스트 길이(현재 원소 개수)
private int extendRatio = 2; // 리스트의 용량을 확장할 때마다 적용하는 배수
/* 생성자 */
public MyList() {
arr = new int[capacity];
}
/* 리스트 길이(현재 원소 개수) 반환 */
public int size() {
return size;
}
/* 리스트 용량 반환 */
public int capacity() {
return capacity;
}
/* 원소 접근 */
public int get(int index) {
// 인덱스가 범위를 벗어나면 예외를 발생시킨다. 아래에서도 동일하다
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("인덱스가 범위를 벗어났다");
return arr[index];
}
/* 원소 갱신 */
public void set(int index, int num) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("인덱스가 범위를 벗어났다");
arr[index] = num;
}
/* 맨 뒤에 원소 추가 */
public void add(int num) {
// 원소 개수가 용량을 초과하면 용량 확장을 수행한다
if (size == capacity())
extendCapacity();
arr[size] = num;
// 원소 개수를 갱신한다
size++;
}
/* 중간에 원소 삽입 */
public void insert(int index, int num) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("인덱스가 범위를 벗어났다");
// 원소 개수가 용량을 초과하면 용량 확장을 수행한다
if (size == capacity())
extendCapacity();
// 인덱스 index와 그 뒤의 원소를 모두 한 칸씩 뒤로 이동한다
for (int j = size - 1; j >= index; j--) {
arr[j + 1] = arr[j];
}
arr[index] = num;
// 원소 개수를 갱신한다
size++;
}
/* 원소 삭제 */
public int remove(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("인덱스가 범위를 벗어났다");
int num = arr[index];
// 인덱스 index 뒤의 원소를 모두 한 칸씩 앞으로 이동한다
for (int j = index; j < size - 1; j++) {
arr[j] = arr[j + 1];
}
// 원소 개수를 갱신한다
size--;
// 삭제한 원소를 반환한다
return num;
}
/* 리스트 용량 확장 */
public void extendCapacity() {
// 길이가 원래 배열의 extendRatio배인 새 배열을 생성하고, 원래 배열을 새 배열에 복사한다
arr = Arrays.copyOf(arr, capacity() * extendRatio);
// 리스트 용량을 갱신한다
capacity = arr.length;
}
/* 리스트를 배열로 변환 */
public int[] toArray() {
int size = size();
// 유효한 길이 범위 안의 리스트 원소만 변환한다
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = get(i);
}
return arr;
}
}
public class my_list {
/* 실행 코드 */
public static void main(String[] args) {
/* 리스트 초기화 */
MyList nums = new MyList();
/* 맨 뒤에 원소 추가 */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
System.out.println("리스트 nums = " + Arrays.toString(nums.toArray()) +
" , 용량 = " + nums.capacity() + " , 길이 = " + nums.size());
/* 중간에 원소 삽입 */
nums.insert(3, 6);
System.out.println("인덱스 3에 숫자 6을 삽입한 후 nums = " + Arrays.toString(nums.toArray()));
/* 원소 삭제 */
nums.remove(3);
System.out.println("인덱스 3의 원소를 삭제한 후 nums = " + Arrays.toString(nums.toArray()));
/* 원소 접근 */
int num = nums.get(1);
System.out.println("인덱스 1의 원소에 접근하여 얻은 num = " + num);
/* 원소 갱신 */
nums.set(1, 0);
System.out.println("인덱스 1의 원소를 0으로 갱신한 후 nums = " + Arrays.toString(nums.toArray()));
/* 용량 확장 동작 테스트 */
for (int i = 0; i < 10; i++) {
// i = 5일 때 리스트 길이가 용량을 초과하므로 용량 확장이 수행된다
nums.add(i);
}
System.out.println("용량을 확장한 후 리스트 nums = " + Arrays.toString(nums.toArray()) +
" , 용량 = " + nums.capacity() + " , 길이 = " + nums.size());
}
}

View File

@@ -0,0 +1,77 @@
/**
* File: n_queens.java
* Created Time: 2023-05-04
* Author: krahets (krahets@163.com)
*/
package chapter_backtracking;
import java.util.*;
public class n_queens {
/* 백트래킹 알고리즘: n-퀸 */
public static void backtrack(int row, int n, List<List<String>> state, List<List<List<String>>> res,
boolean[] cols, boolean[] diags1, boolean[] diags2) {
// 모든 행에 배치했으면 해를 기록한다
if (row == n) {
List<List<String>> copyState = new ArrayList<>();
for (List<String> sRow : state) {
copyState.add(new ArrayList<>(sRow));
}
res.add(copyState);
return;
}
// 모든 열을 순회한다
for (int col = 0; col < n; col++) {
// 해당 칸이 속한 주대각선과 부대각선을 계산한다
int diag1 = row - col + n - 1;
int diag2 = row + col;
// 가지치기: 해당 칸이 속한 열, 주대각선, 부대각선에 퀸이 있으면 안 된다
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
// 시도: 해당 칸에 퀸을 놓는다
state.get(row).set(col, "Q");
cols[col] = diags1[diag1] = diags2[diag2] = true;
// 다음 행에 배치한다
backtrack(row + 1, n, state, res, cols, diags1, diags2);
// 되돌리기: 해당 칸을 빈칸으로 되돌린다
state.get(row).set(col, "#");
cols[col] = diags1[diag1] = diags2[diag2] = false;
}
}
}
/* n-퀸 문제 풀기 */
public static List<List<List<String>>> nQueens(int n) {
// n*n 크기의 체스판을 초기화한다. 'Q'는 퀸, '#'은 빈칸을 나타낸다
List<List<String>> state = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<String> row = new ArrayList<>();
for (int j = 0; j < n; j++) {
row.add("#");
}
state.add(row);
}
boolean[] cols = new boolean[n]; // 열에 퀸이 있는지 기록한다
boolean[] diags1 = new boolean[2 * n - 1]; // 주대각선에 퀸이 있는지 기록한다
boolean[] diags2 = new boolean[2 * n - 1]; // 부대각선에 퀸이 있는지 기록한다
List<List<List<String>>> res = new ArrayList<>();
backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}
public static void main(String[] args) {
int n = 4;
List<List<List<String>>> res = nQueens(n);
System.out.println("입력한 체스판의 가로와 세로 길이: " + n);
System.out.println("퀸을 배치하는 방법은 총 " + res.size() + " 가지이다");
for (List<List<String>> state : res) {
System.out.println("--------------------");
for (List<String> row : state) {
System.out.println(row);
}
}
}
}

View File

@@ -0,0 +1,51 @@
/**
* File: permutations_i.java
* Created Time: 2023-04-24
* Author: krahets (krahets@163.com)
*/
package chapter_backtracking;
import java.util.*;
public class permutations_i {
/* 백트래킹 알고리즘: 모든 순열 I */
public static void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
// 상태의 길이가 원소 개수와 같으면 해를 기록한다
if (state.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// 모든 선택지를 순회한다
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 가지치기: 원소를 중복하여 선택할 수 없다
if (!selected[i]) {
// 시도: 선택하고 상태를 갱신한다
selected[i] = true;
state.add(choice);
// 다음 선택을 진행한다
backtrack(state, choices, selected, res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
selected[i] = false;
state.remove(state.size() - 1);
}
}
}
/* 모든 순열 I */
static List<List<Integer>> permutationsI(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
return res;
}
public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
List<List<Integer>> res = permutationsI(nums);
System.out.println("입력 배열 nums = " + Arrays.toString(nums));
System.out.println("모든 순열 res = " + res);
}
}

View File

@@ -0,0 +1,53 @@
/**
* File: permutations_ii.java
* Created Time: 2023-04-24
* Author: krahets (krahets@163.com)
*/
package chapter_backtracking;
import java.util.*;
public class permutations_ii {
/* 백트래킹 알고리즘: 모든 순열 II */
static void backtrack(List<Integer> state, int[] choices, boolean[] selected, List<List<Integer>> res) {
// 상태의 길이가 원소 개수와 같으면 해를 기록한다
if (state.size() == choices.length) {
res.add(new ArrayList<Integer>(state));
return;
}
// 모든 선택지를 순회한다
Set<Integer> duplicated = new HashSet<Integer>();
for (int i = 0; i < choices.length; i++) {
int choice = choices[i];
// 가지치기: 원소를 중복하여 선택할 수 없으며, 값이 같은 원소도 중복하여 선택할 수 없다
if (!selected[i] && !duplicated.contains(choice)) {
// 시도: 선택하고 상태를 갱신한다
duplicated.add(choice); // 선택한 원소의 값을 기록한다
selected[i] = true;
state.add(choice);
// 다음 선택을 진행한다
backtrack(state, choices, selected, res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
selected[i] = false;
state.remove(state.size() - 1);
}
}
}
/* 모든 순열 II */
static List<List<Integer>> permutationsII(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
backtrack(new ArrayList<Integer>(), nums, new boolean[nums.length], res);
return res;
}
public static void main(String[] args) {
int[] nums = { 1, 2, 2 };
List<List<Integer>> res = permutationsII(nums);
System.out.println("입력 배열 nums = " + Arrays.toString(nums));
System.out.println("모든 순열 res = " + res);
}
}

View File

@@ -0,0 +1,44 @@
/**
* File: preorder_traversal_i_compact.java
* Created Time: 2023-04-16
* Author: krahets (krahets@163.com)
*/
package chapter_backtracking;
import utils.*;
import java.util.*;
public class preorder_traversal_i_compact {
static List<TreeNode> res;
/* 전위 순회: 예제 1 */
static void preOrder(TreeNode root) {
if (root == null) {
return;
}
if (root.val == 7) {
// 해를 기록한다
res.add(root);
}
preOrder(root.left);
preOrder(root.right);
}
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\n이진 트리 초기화");
PrintUtil.printTree(root);
// 전위 순회
res = new ArrayList<>();
preOrder(root);
System.out.println("\n값이 7인 모든 노드 출력");
List<Integer> vals = new ArrayList<>();
for (TreeNode node : res) {
vals.add(node.val);
}
System.out.println(vals);
}
}

View File

@@ -0,0 +1,52 @@
/**
* File: preorder_traversal_ii_compact.java
* Created Time: 2023-04-16
* Author: krahets (krahets@163.com)
*/
package chapter_backtracking;
import utils.*;
import java.util.*;
public class preorder_traversal_ii_compact {
static List<TreeNode> path;
static List<List<TreeNode>> res;
/* 전위 순회: 예제 2 */
static void preOrder(TreeNode root) {
if (root == null) {
return;
}
// 시도
path.add(root);
if (root.val == 7) {
// 해를 기록한다
res.add(new ArrayList<>(path));
}
preOrder(root.left);
preOrder(root.right);
// 되돌리기
path.remove(path.size() - 1);
}
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\n이진 트리 초기화");
PrintUtil.printTree(root);
// 전위 순회
path = new ArrayList<>();
res = new ArrayList<>();
preOrder(root);
System.out.println("\n루트 노드에서 노드 7까지의 모든 경로 출력");
for (List<TreeNode> path : res) {
List<Integer> vals = new ArrayList<>();
for (TreeNode node : path) {
vals.add(node.val);
}
System.out.println(vals);
}
}
}

View File

@@ -0,0 +1,53 @@
/**
* File: preorder_traversal_iii_compact.java
* Created Time: 2023-04-16
* Author: krahets (krahets@163.com)
*/
package chapter_backtracking;
import utils.*;
import java.util.*;
public class preorder_traversal_iii_compact {
static List<TreeNode> path;
static List<List<TreeNode>> res;
/* 전위 순회: 예제 3 */
static void preOrder(TreeNode root) {
// 가지치기
if (root == null || root.val == 3) {
return;
}
// 시도
path.add(root);
if (root.val == 7) {
// 해를 기록한다
res.add(new ArrayList<>(path));
}
preOrder(root.left);
preOrder(root.right);
// 되돌리기
path.remove(path.size() - 1);
}
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\n이진 트리 초기화");
PrintUtil.printTree(root);
// 전위 순회
path = new ArrayList<>();
res = new ArrayList<>();
preOrder(root);
System.out.println("\n루트 노드에서 노드 7까지의 모든 경로 출력. 경로에는 값이 3인 노드가 포함되지 않는다");
for (List<TreeNode> path : res) {
List<Integer> vals = new ArrayList<>();
for (TreeNode node : path) {
vals.add(node.val);
}
System.out.println(vals);
}
}
}

View File

@@ -0,0 +1,77 @@
/**
* File: preorder_traversal_iii_template.java
* Created Time: 2023-04-16
* Author: krahets (krahets@163.com)
*/
package chapter_backtracking;
import utils.*;
import java.util.*;
public class preorder_traversal_iii_template {
/* 현재 상태가 해인지 판단 */
static boolean isSolution(List<TreeNode> state) {
return !state.isEmpty() && state.get(state.size() - 1).val == 7;
}
/* 해를 기록한다 */
static void recordSolution(List<TreeNode> state, List<List<TreeNode>> res) {
res.add(new ArrayList<>(state));
}
/* 현재 상태에서 해당 선택이 유효한지 판단 */
static boolean isValid(List<TreeNode> state, TreeNode choice) {
return choice != null && choice.val != 3;
}
/* 상태 갱신 */
static void makeChoice(List<TreeNode> state, TreeNode choice) {
state.add(choice);
}
/* 상태 복원 */
static void undoChoice(List<TreeNode> state, TreeNode choice) {
state.remove(state.size() - 1);
}
/* 백트래킹 알고리즘: 예제 3 */
static void backtrack(List<TreeNode> state, List<TreeNode> choices, List<List<TreeNode>> res) {
// 해인지 확인한다
if (isSolution(state)) {
// 해를 기록한다
recordSolution(state, res);
}
// 모든 선택지를 순회한다
for (TreeNode choice : choices) {
// 가지치기: 선택이 유효한지 확인한다
if (isValid(state, choice)) {
// 시도: 선택하고 상태를 갱신한다
makeChoice(state, choice);
// 다음 선택을 진행한다
backtrack(state, Arrays.asList(choice.left, choice.right), res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
undoChoice(state, choice);
}
}
}
public static void main(String[] args) {
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 7, 3, 4, 5, 6, 7));
System.out.println("\n이진 트리 초기화");
PrintUtil.printTree(root);
// 백트래킹 알고리즘
List<List<TreeNode>> res = new ArrayList<>();
backtrack(new ArrayList<>(), Arrays.asList(root), res);
System.out.println("\n값이 3인 노드를 포함하지 않는 조건으로, 루트 노드에서 노드 7까지의 모든 경로 출력");
for (List<TreeNode> path : res) {
List<Integer> vals = new ArrayList<>();
for (TreeNode node : path) {
vals.add(node.val);
}
System.out.println(vals);
}
}
}

View File

@@ -0,0 +1,55 @@
/**
* File: subset_sum_i.java
* Created Time: 2023-06-21
* Author: krahets (krahets@163.com)
*/
package chapter_backtracking;
import java.util.*;
public class subset_sum_i {
/* 백트래킹 알고리즘: 부분 집합 합 I */
static void backtrack(List<Integer> state, int target, int[] choices, int start, List<List<Integer>> res) {
// 부분 집합의 합이 target과 같으면 해를 기록한다
if (target == 0) {
res.add(new ArrayList<>(state));
return;
}
// 모든 선택지를 순회한다
// 가지치기 2: start부터 순회하여 중복 부분 집합 생성을 방지한다
for (int i = start; i < choices.length; i++) {
// 가지치기 1: 부분 집합의 합이 target을 초과하면 즉시 반복문을 종료한다
// 배열이 정렬되어 있어 뒤의 원소가 더 크므로, 부분 집합의 합이 반드시 target을 초과하기 때문이다
if (target - choices[i] < 0) {
break;
}
// 시도: 선택하고 target, start를 갱신한다
state.add(choices[i]);
// 다음 선택을 진행한다
backtrack(state, target - choices[i], choices, i, res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
state.remove(state.size() - 1);
}
}
/* 부분 집합 합 I 풀기 */
static List<List<Integer>> subsetSumI(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // 상태(부분 집합)
Arrays.sort(nums); // nums를 정렬한다
int start = 0; // 순회 시작 위치
List<List<Integer>> res = new ArrayList<>(); // 결과 리스트(부분 집합 리스트)
backtrack(state, target, nums, start, res);
return res;
}
public static void main(String[] args) {
int[] nums = { 3, 4, 5 };
int target = 9;
List<List<Integer>> res = subsetSumI(nums, target);
System.out.println("입력 배열 nums = " + Arrays.toString(nums) + ", target = " + target);
System.out.println("부분 집합의 합: " + target + " ; 해당하는 모든 부분 집합 res = " + res);
}
}

View File

@@ -0,0 +1,53 @@
/**
* File: subset_sum_i_naive.java
* Created Time: 2023-06-21
* Author: krahets (krahets@163.com)
*/
package chapter_backtracking;
import java.util.*;
public class subset_sum_i_naive {
/* 백트래킹 알고리즘: 부분 집합 합 I */
static void backtrack(List<Integer> state, int target, int total, int[] choices, List<List<Integer>> res) {
// 부분 집합의 합이 target과 같으면 해를 기록한다
if (total == target) {
res.add(new ArrayList<>(state));
return;
}
// 모든 선택지를 순회한다
for (int i = 0; i < choices.length; i++) {
// 가지치기: 부분 집합의 합이 target을 초과하면 해당 선택을 건너뛴다
if (total + choices[i] > target) {
continue;
}
// 시도: 선택하고 원소의 합 total을 갱신한다
state.add(choices[i]);
// 다음 선택을 진행한다
backtrack(state, target, total + choices[i], choices, res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
state.remove(state.size() - 1);
}
}
/* 부분 집합 합 I 풀기(중복 부분 집합 포함) */
static List<List<Integer>> subsetSumINaive(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // 상태(부분 집합)
int total = 0; // 부분 집합의 합
List<List<Integer>> res = new ArrayList<>(); // 결과 리스트(부분 집합 리스트)
backtrack(state, target, total, nums, res);
return res;
}
public static void main(String[] args) {
int[] nums = { 3, 4, 5 };
int target = 9;
List<List<Integer>> res = subsetSumINaive(nums, target);
System.out.println("입력 배열 nums = " + Arrays.toString(nums) + ", target = " + target);
System.out.println("부분 집합의 합: " + target + " ; 해당하는 모든 부분 집합 res = " + res);
System.out.println("이 방법의 출력 결과에는 중복 집합이 포함된다");
}
}

View File

@@ -0,0 +1,60 @@
/**
* File: subset_sum_ii.java
* Created Time: 2023-06-21
* Author: krahets (krahets@163.com)
*/
package chapter_backtracking;
import java.util.*;
public class subset_sum_ii {
/* 백트래킹 알고리즘: 부분 집합 합 II */
static void backtrack(List<Integer> state, int target, int[] choices, int start, List<List<Integer>> res) {
// 부분 집합의 합이 target과 같으면 해를 기록한다
if (target == 0) {
res.add(new ArrayList<>(state));
return;
}
// 모든 선택지를 순회한다
// 가지치기 2: start부터 순회하여 중복 부분 집합 생성을 방지한다
// 가지치기 3: start부터 순회하여 같은 원소의 중복 선택을 방지한다
for (int 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.add(choices[i]);
// 다음 선택을 진행한다
backtrack(state, target - choices[i], choices, i + 1, res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
state.remove(state.size() - 1);
}
}
/* 부분 집합 합 II 풀기 */
static List<List<Integer>> subsetSumII(int[] nums, int target) {
List<Integer> state = new ArrayList<>(); // 상태(부분 집합)
Arrays.sort(nums); // nums를 정렬한다
int start = 0; // 순회 시작 위치
List<List<Integer>> res = new ArrayList<>(); // 결과 리스트(부분 집합 리스트)
backtrack(state, target, nums, start, res);
return res;
}
public static void main(String[] args) {
int[] nums = { 4, 4, 5 };
int target = 9;
List<List<Integer>> res = subsetSumII(nums, target);
System.out.println("입력 배열 nums = " + Arrays.toString(nums) + ", target = " + target);
System.out.println("부분 집합의 합: " + target + " ; 해당하는 모든 부분 집합 res = " + res);
}
}

View File

@@ -0,0 +1,62 @@
/**
* File: complexity_exercises.java
* Created Time: 2026-08-18
* Author: Hello Algo Team
*/
package chapter_computational_complexity;
public class complexity_exercises {
/* 반복으로 합 구하기 */
static int sumIter(int n) {
int res = 0;
for (int i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* 재귀로 합 구하기 */
static int sumRecur(int n) {
if (n == 1) {
return 1;
}
return n + sumRecur(n - 1);
}
/* 선형 차수 반복문 */
static int linearLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
res += i;
}
return res;
}
/* 제곱 차수 반복문 */
static int quadraticLoop(int n) {
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
res += j;
}
}
return res;
}
/* 로그 차수 반복문 */
static int logarithmicLoop(int n) {
while (n > 1) {
n /= 2;
}
return n;
}
public static void main(String[] args) {
assert sumIter(1) == 1 && sumRecur(1) == 1;
assert sumIter(4) == 10 && sumRecur(4) == 10;
assert linearLoop(4) == 6;
assert quadraticLoop(4) == 20;
assert logarithmicLoop(4) == 1 && logarithmicLoop(5) == 1;
}
}

View File

@@ -0,0 +1,76 @@
/**
* File: iteration.java
* Created Time: 2023-08-24
* Author: krahets (krahets@163.com)
*/
package chapter_computational_complexity;
public class iteration {
/* for 반복문 */
static int forLoop(int n) {
int res = 0;
// 반복문으로 1, 2, ..., n-1, n의 합을 구한다
for (int i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* while 반복문 */
static int whileLoop(int n) {
int res = 0;
int i = 1; // 조건 변수를 초기화한다
// 반복문으로 1, 2, ..., n-1, n의 합을 구한다
while (i <= n) {
res += i;
i++; // 조건 변수를 갱신한다
}
return res;
}
/* while 반복문(두 번 갱신) */
static int whileLoopII(int n) {
int res = 0;
int i = 1; // 조건 변수를 초기화한다
// 반복문으로 1, 4, 10, ...의 합을 구한다
while (i <= n) {
res += i;
// 조건 변수를 갱신한다
i++;
i *= 2;
}
return res;
}
/* 이중 for 반복문 */
static String nestedForLoop(int n) {
StringBuilder res = new StringBuilder();
// i = 1, 2, ..., n-1, n을 반복한다
for (int i = 1; i <= n; i++) {
// j = 1, 2, ..., n-1, n을 반복한다
for (int j = 1; j <= n; j++) {
res.append("(" + i + ", " + j + "), ");
}
}
return res.toString();
}
/* 실행 코드 */
public static void main(String[] args) {
int n = 5;
int res;
res = forLoop(n);
System.out.println("\nfor 반복문으로 구한 합 res = " + res);
res = whileLoop(n);
System.out.println("\nwhile 반복문으로 구한 합 res = " + res);
res = whileLoopII(n);
System.out.println("\nwhile 반복문(두 번 갱신)으로 구한 합 res = " + res);
String resStr = nestedForLoop(n);
System.out.println("\n이중 for 반복문의 순회 결과 " + resStr);
}
}

View File

@@ -0,0 +1,79 @@
/**
* File: recursion.java
* Created Time: 2023-08-24
* Author: krahets (krahets@163.com)
*/
package chapter_computational_complexity;
import java.util.Stack;
public class recursion {
/* 재귀 */
static int recur(int n) {
// 종료 조건
if (n == 1)
return 1;
// 내려가기: 재귀 호출
int res = recur(n - 1);
// 돌아오기: 결과 반환
return n + res;
}
/* 반복으로 재귀 구현 */
static int forLoopRecur(int n) {
// 명시적인 스택을 사용하여 시스템 호출 스택을 모방한다
Stack<Integer> stack = new Stack<>();
int res = 0;
// 내려가기: 재귀 호출
for (int i = n; i > 0; i--) {
// 스택에 삽입하여 내려가는 과정을 모방한다
stack.push(i);
}
// 돌아오기: 결과 반환
while (!stack.isEmpty()) {
// 스택에서 꺼내어 돌아오는 과정을 모방한다
res += stack.pop();
}
// res = 1+2+3+...+n
return res;
}
/* 꼬리 재귀 */
static int tailRecur(int n, int res) {
// 종료 조건
if (n == 0)
return res;
// 꼬리 재귀 호출
return tailRecur(n - 1, res + n);
}
/* 피보나치 수열: 재귀 */
static int fib(int n) {
// 종료 조건 f(1) = 0, f(2) = 1
if (n == 1 || n == 2)
return n - 1;
// 재귀 호출 f(n) = f(n-1) + f(n-2)
int res = fib(n - 1) + fib(n - 2);
// 결과 f(n)을 반환한다
return res;
}
/* 실행 코드 */
public static void main(String[] args) {
int n = 5;
int res;
res = recur(n);
System.out.println("\n재귀 함수로 구한 합 res = " + res);
res = forLoopRecur(n);
System.out.println("\n반복으로 재귀를 구현하여 구한 합 res = " + res);
res = tailRecur(n, 0);
System.out.println("\n꼬리 재귀 함수로 구한 합 res = " + res);
res = fib(n);
System.out.println("\n피보나치 수열의 항 번호: " + n + " ; 해당 항의 값: " + res);
}
}

View File

@@ -0,0 +1,110 @@
/**
* File: space_complexity.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_computational_complexity;
import utils.*;
import java.util.*;
public class space_complexity {
/* 함수 */
static int function() {
// 몇 가지 연산을 수행한다
return 0;
}
/* 상수 차수 */
static void constant(int n) {
// 상수, 변수, 객체는 O(1) 공간을 차지한다
final int a = 0;
int b = 0;
int[] nums = new int[10000];
ListNode node = new ListNode(0);
// 반복문 안의 변수는 O(1) 공간을 차지한다
for (int i = 0; i < n; i++) {
int c = 0;
}
// 반복문 안의 함수는 O(1) 공간을 차지한다
for (int i = 0; i < n; i++) {
function();
}
}
/* 선형 차수 */
static void linear(int n) {
// 길이가 n인 배열은 O(n) 공간을 차지한다
int[] nums = new int[n];
// 길이가 n인 리스트는 O(n) 공간을 차지한다
List<ListNode> nodes = new ArrayList<>();
for (int i = 0; i < n; i++) {
nodes.add(new ListNode(i));
}
// 길이가 n인 해시 테이블은 O(n) 공간을 차지한다
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(i, String.valueOf(i));
}
}
/* 선형 차수(재귀 구현) */
static void linearRecur(int n) {
System.out.println("재귀 n = " + n);
if (n == 1)
return;
linearRecur(n - 1);
}
/* 제곱 차수 */
static void quadratic(int n) {
// 행렬은 O(n^2) 공간을 차지한다
int[][] numMatrix = new int[n][n];
// 이차원 리스트는 O(n^2) 공간을 차지한다
List<List<Integer>> numList = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> tmp = new ArrayList<>();
for (int j = 0; j < n; j++) {
tmp.add(0);
}
numList.add(tmp);
}
}
/* 제곱 차수(재귀 구현) */
static int quadraticRecur(int n) {
if (n <= 0)
return 0;
// 배열 nums의 길이는 n, n-1, ..., 2, 1이다
int[] nums = new int[n];
System.out.println("재귀 n = " + n + " 일 때 nums의 길이 = " + nums.length);
return quadraticRecur(n - 1);
}
/* 지수 차수(포화 이진 트리 구성) */
static TreeNode buildTree(int n) {
if (n == 0)
return null;
TreeNode root = new TreeNode(0);
root.left = buildTree(n - 1);
root.right = buildTree(n - 1);
return root;
}
/* 실행 코드 */
public static void main(String[] args) {
int n = 5;
// 상수 차수
constant(n);
// 선형 차수
linear(n);
linearRecur(n);
// 제곱 차수
quadratic(n);
quadraticRecur(n);
// 지수 차수
TreeNode root = buildTree(n);
PrintUtil.printTree(root);
}
}

View File

@@ -0,0 +1,167 @@
/**
* File: time_complexity.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_computational_complexity;
public class time_complexity {
/* 상수 차수 */
static int constant(int n) {
int count = 0;
int size = 100000;
for (int i = 0; i < size; i++)
count++;
return count;
}
/* 선형 차수 */
static int linear(int n) {
int count = 0;
for (int i = 0; i < n; i++)
count++;
return count;
}
/* 선형 차수(배열 순회) */
static int arrayTraversal(int[] nums) {
int count = 0;
// 반복 횟수는 배열 길이에 비례한다
for (int num : nums) {
count++;
}
return count;
}
/* 제곱 차수 */
static int quadratic(int n) {
int count = 0;
// 반복 횟수는 데이터 크기 n의 제곱에 비례한다
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
count++;
}
}
return count;
}
/* 제곱 차수(버블 정렬) */
static int bubbleSort(int[] nums) {
int count = 0; // 카운터
// 바깥쪽 반복문: 정렬되지 않은 구간은 [0, i]이다
for (int i = nums.length - 1; i > 0; i--) {
// 안쪽 반복문: 정렬되지 않은 구간 [0, i]의 최댓값을 교환하여 이 구간의 맨 오른쪽으로 옮긴다
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// nums[j]와 nums[j + 1]을 교환한다
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // 원소 교환에는 단위 연산 3회가 포함된다
}
}
}
return count;
}
/* 지수 차수(반복문 구현) */
static int exponential(int n) {
int count = 0, base = 1;
// 세포가 매번 둘로 나뉘어 수열 1, 2, 4, 8, ..., 2^(n-1)을 이룬다
for (int i = 0; i < n; i++) {
for (int j = 0; j < base; j++) {
count++;
}
base *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* 지수 차수(재귀 구현) */
static int expRecur(int n) {
if (n == 1)
return 1;
return expRecur(n - 1) + expRecur(n - 1) + 1;
}
/* 로그 차수(반복문 구현) */
static int logarithmic(int n) {
int count = 0;
while (n > 1) {
n = n / 2;
count++;
}
return count;
}
/* 로그 차수(재귀 구현) */
static int logRecur(int n) {
if (n <= 1)
return 0;
return logRecur(n / 2) + 1;
}
/* 선형 로그 차수 */
static int linearLogRecur(int n) {
if (n <= 1)
return 1;
int count = linearLogRecur(n / 2) + linearLogRecur(n / 2);
for (int i = 0; i < n; i++) {
count++;
}
return count;
}
/* 팩토리얼 차수(재귀 구현) */
static int factorialRecur(int n) {
if (n == 0)
return 1;
int count = 0;
// 하나에서 n개로 분열한다
for (int i = 0; i < n; i++) {
count += factorialRecur(n - 1);
}
return count;
}
/* 실행 코드 */
public static void main(String[] args) {
// n을 바꾸어 실행하면서 각 복잡도에서 연산 횟수가 어떻게 변하는지 살펴볼 수 있다
int n = 8;
System.out.println("입력 데이터 크기 n = " + n);
int count = constant(n);
System.out.println("상수 차수의 연산 횟수 = " + count);
count = linear(n);
System.out.println("선형 차수의 연산 횟수 = " + count);
count = arrayTraversal(new int[n]);
System.out.println("선형 차수(배열 순회)의 연산 횟수 = " + count);
count = quadratic(n);
System.out.println("제곱 차수의 연산 횟수 = " + count);
int[] nums = new int[n];
for (int i = 0; i < n; i++)
nums[i] = n - i; // [n,n-1,...,2,1]
count = bubbleSort(nums);
System.out.println("제곱 차수(버블 정렬)의 연산 횟수 = " + count);
count = exponential(n);
System.out.println("지수 차수(반복문 구현)의 연산 횟수 = " + count);
count = expRecur(n);
System.out.println("지수 차수(재귀 구현)의 연산 횟수 = " + count);
count = logarithmic(n);
System.out.println("로그 차수(반복문 구현)의 연산 횟수 = " + count);
count = logRecur(n);
System.out.println("로그 차수(재귀 구현)의 연산 횟수 = " + count);
count = linearLogRecur(n);
System.out.println("선형 로그 차수(재귀 구현)의 연산 횟수 = " + count);
count = factorialRecur(n);
System.out.println("팩토리얼 차수(재귀 구현)의 연산 횟수 = " + count);
}
}

View File

@@ -0,0 +1,50 @@
/**
* File: worst_best_time_complexity.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_computational_complexity;
import java.util.*;
public class worst_best_time_complexity {
/* 원소가 { 1, 2, ..., n }이며 순서가 섞인 배열 생성 */
static int[] randomNumbers(int n) {
Integer[] nums = new Integer[n];
// 배열 nums = { 1, 2, 3, ..., n }을 생성한다
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
// 배열 원소를 무작위로 섞는다
Collections.shuffle(Arrays.asList(nums));
// Integer[] -> int[]
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nums[i];
}
return res;
}
/* 배열 nums에서 숫자 1이 있는 인덱스 탐색 */
static int findOne(int[] nums) {
for (int i = 0; i < nums.length; i++) {
// 원소 1이 배열 맨 앞에 있으면 최선 시간 복잡도 O(1)에 도달한다
// 원소 1이 배열 맨 뒤에 있으면 최악 시간 복잡도 O(n)에 도달한다
if (nums[i] == 1)
return i;
}
return -1;
}
/* 실행 코드 */
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int n = 100;
int[] nums = randomNumbers(n);
int index = findOne(nums);
System.out.println("\n배열 [ 1, 2, ..., n ]을 섞은 결과 = " + Arrays.toString(nums));
System.out.println("숫자 1의 인덱스 " + index);
}
}
}

View File

@@ -0,0 +1,45 @@
/**
* File: binary_search_recur.java
* Created Time: 2023-07-17
* Author: krahets (krahets@163.com)
*/
package chapter_divide_and_conquer;
public class binary_search_recur {
/* 이진 탐색: 문제 f(i, j) */
static int dfs(int[] nums, int target, int i, int j) {
// 구간이 비어 있으면 목표 원소가 없다는 뜻이므로 -1을 반환한다
if (i > j) {
return -1;
}
// 중간 인덱스 m을 계산한다
int m = (i + j) / 2;
if (nums[m] < target) {
// 부분 문제 f(m+1, j)를 재귀적으로 푼다
return dfs(nums, target, m + 1, j);
} else if (nums[m] > target) {
// 부분 문제 f(i, m-1)를 재귀적으로 푼다
return dfs(nums, target, i, m - 1);
} else {
// 목표 원소를 찾았으므로 해당 인덱스를 반환한다
return m;
}
}
/* 이진 탐색 */
static int binarySearch(int[] nums, int target) {
int n = nums.length;
// 문제 f(0, n-1)을 푼다
return dfs(nums, target, 0, n - 1);
}
public static void main(String[] args) {
int target = 6;
int[] nums = { 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 };
// 이진 탐색(양 끝을 포함하는 닫힌 구간)
int index = binarySearch(nums, target);
System.out.println("목표 원소 6의 인덱스 = " + index);
}
}

View File

@@ -0,0 +1,51 @@
/**
* File: build_tree.java
* Created Time: 2023-07-17
* Author: krahets (krahets@163.com)
*/
package chapter_divide_and_conquer;
import utils.*;
import java.util.*;
public class build_tree {
/* 이진 트리 구성: 분할 정복 */
static TreeNode dfs(int[] preorder, Map<Integer, Integer> inorderMap, int i, int l, int r) {
// 서브트리 구간이 비어 있으면 종료한다
if (r - l < 0)
return null;
// 루트 노드를 초기화한다
TreeNode root = new TreeNode(preorder[i]);
// m을 조회하여 왼쪽과 오른쪽 서브트리를 나눈다
int m = inorderMap.get(preorder[i]);
// 부분 문제: 왼쪽 서브트리 구성
root.left = dfs(preorder, inorderMap, i + 1, l, m - 1);
// 부분 문제: 오른쪽 서브트리 구성
root.right = dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r);
// 루트 노드를 반환한다
return root;
}
/* 이진 트리 구성 */
static TreeNode buildTree(int[] preorder, int[] inorder) {
// inorder 원소와 인덱스의 대응 관계를 저장할 해시 테이블을 초기화한다
Map<Integer, Integer> inorderMap = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
inorderMap.put(inorder[i], i);
}
TreeNode root = dfs(preorder, inorderMap, 0, 0, inorder.length - 1);
return root;
}
public static void main(String[] args) {
int[] preorder = { 3, 9, 2, 1, 7 };
int[] inorder = { 9, 3, 1, 2, 7 };
System.out.println("전위 순회 = " + Arrays.toString(preorder));
System.out.println("중위 순회 = " + Arrays.toString(inorder));
TreeNode root = buildTree(preorder, inorder);
System.out.println("구성한 이진 트리:");
PrintUtil.printTree(root);
}
}

View File

@@ -0,0 +1,27 @@
/**
* File: fast_power.java
* Created Time: 2026-08-18
* Author: Hello Algo Team
*/
package chapter_divide_and_conquer;
public class fast_power {
/* 빠른 거듭제곱 */
static int fastPow(int x, int n) {
if (n == 0) {
return 1;
}
int half = fastPow(x, n / 2);
if (n % 2 == 0) {
return half * half;
}
return half * half * x;
}
public static void main(String[] args) {
assert fastPow(7, 0) == 1;
assert fastPow(3, 5) == 243;
assert fastPow(2, 6) == 64;
}
}

View File

@@ -0,0 +1,59 @@
/**
* File: hanota.java
* Created Time: 2023-07-17
* Author: krahets (krahets@163.com)
*/
package chapter_divide_and_conquer;
import java.util.*;
public class hanota {
/* 원판 하나 이동 */
static void move(List<Integer> src, List<Integer> tar) {
// src의 맨 위에서 원판 하나를 꺼낸다
Integer pan = src.remove(src.size() - 1);
// 원판을 tar의 맨 위에 놓는다
tar.add(pan);
}
/* 하노이의 탑 문제 f(i) 풀기 */
static void dfs(int i, List<Integer> src, List<Integer> buf, List<Integer> tar) {
// src에 원판이 하나만 남아 있으면 바로 tar로 옮긴다
if (i == 1) {
move(src, tar);
return;
}
// 부분 문제 f(i-1): tar를 이용하여 src의 맨 위 원판 i-1개를 buf로 옮긴다
dfs(i - 1, src, tar, buf);
// 부분 문제 f(1): src에 남은 원판 하나를 tar로 옮긴다
move(src, tar);
// 부분 문제 f(i-1): src를 이용하여 buf의 맨 위 원판 i-1개를 tar로 옮긴다
dfs(i - 1, buf, src, tar);
}
/* 하노이의 탑 문제 풀기 */
static void solveHanota(List<Integer> A, List<Integer> B, List<Integer> C) {
int n = A.size();
// B를 이용하여 A의 맨 위 원판 n개를 C로 옮긴다
dfs(n, A, B, C);
}
public static void main(String[] args) {
// 리스트의 맨 뒤가 기둥의 맨 위이다
List<Integer> A = new ArrayList<>(Arrays.asList(5, 4, 3, 2, 1));
List<Integer> B = new ArrayList<>();
List<Integer> C = new ArrayList<>();
System.out.println("초기 상태:");
System.out.println("A = " + A);
System.out.println("B = " + B);
System.out.println("C = " + C);
solveHanota(A, B, C);
System.out.println("원판 이동을 마친 후:");
System.out.println("A = " + A);
System.out.println("B = " + B);
System.out.println("C = " + C);
}
}

View File

@@ -0,0 +1,44 @@
/**
* File: climbing_stairs_backtrack.java
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.*;
public class climbing_stairs_backtrack {
/* 백트래킹 */
public static void backtrack(List<Integer> choices, int state, int n, List<Integer> res) {
// n번째 계단에 도달하면 방법의 수에 1을 더한다
if (state == n)
res.set(0, res.get(0) + 1);
// 모든 선택지를 순회한다
for (Integer choice : choices) {
// 가지치기: n번째 계단을 넘어갈 수 없다
if (state + choice > n)
continue;
// 시도: 선택하고 상태를 갱신한다
backtrack(choices, state + choice, n, res);
// 되돌리기
}
}
/* 계단 오르기: 백트래킹 */
public static int climbingStairsBacktrack(int n) {
List<Integer> choices = Arrays.asList(1, 2); // 한 계단 또는 두 계단 오르기를 선택할 수 있다
int state = 0; // 0번째 계단에서 오르기 시작한다
List<Integer> res = new ArrayList<>();
res.add(0); // res[0]에 방법의 수를 기록한다
backtrack(choices, state, n, res);
return res.get(0);
}
public static void main(String[] args) {
int n = 9;
int res = climbingStairsBacktrack(n);
System.out.println(String.format("%d개의 계단을 오르는 방법은 총 %d가지이다", n, res));
}
}

View File

@@ -0,0 +1,36 @@
/**
* File: climbing_stairs_constraint_dp.java
* Created Time: 2023-07-01
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
public class climbing_stairs_constraint_dp {
/* 제약 조건이 있는 계단 오르기: 동적 계획법 */
static int climbingStairsConstraintDP(int n) {
if (n == 1 || n == 2) {
return 1;
}
// 부분 문제의 해를 저장할 dp 테이블을 초기화한다
int[][] dp = new int[n + 1][3];
// 초기 상태: 가장 작은 부분 문제의 해를 미리 설정한다
dp[1][1] = 1;
dp[1][2] = 0;
dp[2][1] = 0;
dp[2][2] = 1;
// 상태 전이: 작은 부분 문제부터 점차 큰 부분 문제를 푼다
for (int i = 3; i <= n; i++) {
dp[i][1] = dp[i - 1][2];
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
}
return dp[n][1] + dp[n][2];
}
public static void main(String[] args) {
int n = 9;
int res = climbingStairsConstraintDP(n);
System.out.println(String.format("%d개의 계단을 오르는 방법은 총 %d가지이다", n, res));
}
}

View File

@@ -0,0 +1,31 @@
/**
* File: climbing_stairs_dfs.java
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
public class climbing_stairs_dfs {
/* 탐색 */
public static int dfs(int i) {
// dp[1]과 dp[2]는 이미 알고 있으므로 해당 값을 반환한다
if (i == 1 || i == 2)
return i;
// dp[i] = dp[i-1] + dp[i-2]
int count = dfs(i - 1) + dfs(i - 2);
return count;
}
/* 계단 오르기: 탐색 */
public static int climbingStairsDFS(int n) {
return dfs(n);
}
public static void main(String[] args) {
int n = 9;
int res = climbingStairsDFS(n);
System.out.println(String.format("%d개의 계단을 오르는 방법은 총 %d가지이다", n, res));
}
}

View File

@@ -0,0 +1,41 @@
/**
* File: climbing_stairs_dfs_mem.java
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class climbing_stairs_dfs_mem {
/* 메모이제이션을 이용한 탐색 */
public static int dfs(int i, int[] mem) {
// dp[1]과 dp[2]는 이미 알고 있으므로 해당 값을 반환한다
if (i == 1 || i == 2)
return i;
// dp[i]의 기록이 있으면 해당 값을 바로 반환한다
if (mem[i] != -1)
return mem[i];
// dp[i] = dp[i-1] + dp[i-2]
int count = dfs(i - 1, mem) + dfs(i - 2, mem);
// dp[i]를 기록한다
mem[i] = count;
return count;
}
/* 계단 오르기: 메모이제이션을 이용한 탐색 */
public static int climbingStairsDFSMem(int n) {
// mem[i]는 i번째 계단까지 오르는 전체 방법의 수를 기록하며, -1은 기록이 없음을 나타낸다
int[] mem = new int[n + 1];
Arrays.fill(mem, -1);
return dfs(n, mem);
}
public static void main(String[] args) {
int n = 9;
int res = climbingStairsDFSMem(n);
System.out.println(String.format("%d개의 계단을 오르는 방법은 총 %d가지이다", n, res));
}
}

View File

@@ -0,0 +1,48 @@
/**
* File: climbing_stairs_dp.java
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
public class climbing_stairs_dp {
/* 계단 오르기: 동적 계획법 */
public static int climbingStairsDP(int n) {
if (n == 1 || n == 2)
return n;
// 부분 문제의 해를 저장할 dp 테이블을 초기화한다
int[] dp = new int[n + 1];
// 초기 상태: 가장 작은 부분 문제의 해를 미리 설정한다
dp[1] = 1;
dp[2] = 2;
// 상태 전이: 작은 부분 문제부터 점차 큰 부분 문제를 푼다
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
/* 계단 오르기: 공간을 최적화한 동적 계획법 */
public static int climbingStairsDPComp(int n) {
if (n == 1 || n == 2)
return n;
int a = 1, b = 2;
for (int i = 3; i <= n; i++) {
int tmp = b;
b = a + b;
a = tmp;
}
return b;
}
public static void main(String[] args) {
int n = 9;
int res = climbingStairsDP(n);
System.out.println(String.format("%d개의 계단을 오르는 방법은 총 %d가지이다", n, res));
res = climbingStairsDPComp(n);
System.out.println(String.format("%d개의 계단을 오르는 방법은 총 %d가지이다", n, res));
}
}

View File

@@ -0,0 +1,72 @@
/**
* File: coin_change.java
* Created Time: 2023-07-11
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class coin_change {
/* 동전 교환: 동적 계획법 */
static int coinChangeDP(int[] coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// dp 테이블을 초기화한다
int[][] dp = new int[n + 1][amt + 1];
// 상태 전이: 첫 번째 행과 첫 번째 열
for (int a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// 상태 전이: 나머지 행과 열
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// 목표 금액을 초과하면 동전 i를 선택하지 않는다
dp[i][a] = dp[i - 1][a];
} else {
// 동전 i를 선택하지 않는 경우와 선택하는 경우 중 더 작은 값
dp[i][a] = Math.min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
return dp[n][amt] != MAX ? dp[n][amt] : -1;
}
/* 동전 교환: 공간을 최적화한 동적 계획법 */
static int coinChangeDPComp(int[] coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// dp 테이블을 초기화한다
int[] dp = new int[amt + 1];
Arrays.fill(dp, MAX);
dp[0] = 0;
// 상태 전이
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// 목표 금액을 초과하면 동전 i를 선택하지 않는다
dp[a] = dp[a];
} else {
// 동전 i를 선택하지 않는 경우와 선택하는 경우 중 더 작은 값
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] != MAX ? dp[amt] : -1;
}
public static void main(String[] args) {
int[] coins = { 1, 2, 5 };
int amt = 4;
// 동적 계획법
int res = coinChangeDP(coins, amt);
System.out.println("목표 금액을 만드는 데 필요한 최소 동전 개수: " + res);
// 공간을 최적화한 동적 계획법
res = coinChangeDPComp(coins, amt);
System.out.println("목표 금액을 만드는 데 필요한 최소 동전 개수: " + res);
}
}

View File

@@ -0,0 +1,67 @@
/**
* File: coin_change_ii.java
* Created Time: 2023-07-11
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
public class coin_change_ii {
/* 동전 교환 II: 동적 계획법 */
static int coinChangeIIDP(int[] coins, int amt) {
int n = coins.length;
// dp 테이블을 초기화한다
int[][] dp = new int[n + 1][amt + 1];
// 첫 번째 열을 초기화한다
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// 상태 전이
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// 목표 금액을 초과하면 동전 i를 선택하지 않는다
dp[i][a] = dp[i - 1][a];
} else {
// 동전 i를 선택하지 않는 경우와 선택하는 경우의 방법 수를 더한다
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
}
return dp[n][amt];
}
/* 동전 교환 II: 공간을 최적화한 동적 계획법 */
static int coinChangeIIDPComp(int[] coins, int amt) {
int n = coins.length;
// dp 테이블을 초기화한다
int[] dp = new int[amt + 1];
dp[0] = 1;
// 상태 전이
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// 목표 금액을 초과하면 동전 i를 선택하지 않는다
dp[a] = dp[a];
} else {
// 동전 i를 선택하지 않는 경우와 선택하는 경우의 방법 수를 더한다
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
return dp[amt];
}
public static void main(String[] args) {
int[] coins = { 1, 2, 5 };
int amt = 5;
// 동적 계획법
int res = coinChangeIIDP(coins, amt);
System.out.println("목표 금액을 만드는 동전 조합의 수: " + res);
// 공간을 최적화한 동적 계획법
res = coinChangeIIDPComp(coins, amt);
System.out.println("목표 금액을 만드는 동전 조합의 수: " + res);
}
}

View File

@@ -0,0 +1,139 @@
/**
* File: edit_distance.java
* Created Time: 2023-07-13
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class edit_distance {
/* 편집 거리: 완전 탐색 */
static int editDistanceDFS(String s, String t, int i, int j) {
// s와 t가 모두 비어 있으면 0을 반환한다
if (i == 0 && j == 0)
return 0;
// s가 비어 있으면 t의 길이를 반환한다
if (i == 0)
return j;
// t가 비어 있으면 s의 길이를 반환한다
if (j == 0)
return i;
// 두 문자가 같으면 두 문자를 바로 건너뛴다
if (s.charAt(i - 1) == t.charAt(j - 1))
return editDistanceDFS(s, t, i - 1, j - 1);
// 최소 편집 횟수 = 삽입, 삭제, 교체 세 연산에 대한 최소 편집 횟수 + 1
int insert = editDistanceDFS(s, t, i, j - 1);
int delete = editDistanceDFS(s, t, i - 1, j);
int replace = editDistanceDFS(s, t, i - 1, j - 1);
// 최소 편집 횟수를 반환한다
return Math.min(Math.min(insert, delete), replace) + 1;
}
/* 편집 거리: 메모이제이션을 이용한 탐색 */
static int editDistanceDFSMem(String s, String t, int[][] mem, int i, int j) {
// s와 t가 모두 비어 있으면 0을 반환한다
if (i == 0 && j == 0)
return 0;
// s가 비어 있으면 t의 길이를 반환한다
if (i == 0)
return j;
// t가 비어 있으면 s의 길이를 반환한다
if (j == 0)
return i;
// 기록이 이미 있으면 해당 값을 바로 반환한다
if (mem[i][j] != -1)
return mem[i][j];
// 두 문자가 같으면 두 문자를 바로 건너뛴다
if (s.charAt(i - 1) == t.charAt(j - 1))
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
// 최소 편집 횟수 = 삽입, 삭제, 교체 세 연산에 대한 최소 편집 횟수 + 1
int insert = editDistanceDFSMem(s, t, mem, i, j - 1);
int delete = editDistanceDFSMem(s, t, mem, i - 1, j);
int replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
// 최소 편집 횟수를 기록하고 반환한다
mem[i][j] = Math.min(Math.min(insert, delete), replace) + 1;
return mem[i][j];
}
/* 편집 거리: 동적 계획법 */
static int editDistanceDP(String s, String t) {
int n = s.length(), m = t.length();
int[][] dp = new int[n + 1][m + 1];
// 상태 전이: 첫 번째 행과 첫 번째 열
for (int i = 1; i <= n; i++) {
dp[i][0] = i;
}
for (int j = 1; j <= m; j++) {
dp[0][j] = j;
}
// 상태 전이: 나머지 행과 열
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s.charAt(i - 1) == t.charAt(j - 1)) {
// 두 문자가 같으면 두 문자를 바로 건너뛴다
dp[i][j] = dp[i - 1][j - 1];
} else {
// 최소 편집 횟수 = 삽입, 삭제, 교체 세 연산에 대한 최소 편집 횟수 + 1
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
}
}
}
return dp[n][m];
}
/* 편집 거리: 공간을 최적화한 동적 계획법 */
static int editDistanceDPComp(String s, String t) {
int n = s.length(), m = t.length();
int[] dp = new int[m + 1];
// 상태 전이: 첫 번째 행
for (int j = 1; j <= m; j++) {
dp[j] = j;
}
// 상태 전이: 나머지 행
for (int i = 1; i <= n; i++) {
// 상태 전이: 첫 번째 열
int leftup = dp[0]; // dp[i-1, j-1]을 임시로 저장한다
dp[0] = i;
// 상태 전이: 나머지 열
for (int j = 1; j <= m; j++) {
int temp = dp[j];
if (s.charAt(i - 1) == t.charAt(j - 1)) {
// 두 문자가 같으면 두 문자를 바로 건너뛴다
dp[j] = leftup;
} else {
// 최소 편집 횟수 = 삽입, 삭제, 교체 세 연산에 대한 최소 편집 횟수 + 1
dp[j] = Math.min(Math.min(dp[j - 1], dp[j]), leftup) + 1;
}
leftup = temp; // 다음 반복의 dp[i-1, j-1]로 갱신한다
}
}
return dp[m];
}
public static void main(String[] args) {
String s = "bag";
String t = "pack";
int n = s.length(), m = t.length();
// 완전 탐색
int res = editDistanceDFS(s, t, n, m);
System.out.println("변경: " + s + " → " + t + " 변경에 필요한 최소 편집 횟수: " + res + " 회");
// 메모이제이션을 이용한 탐색
int[][] mem = new int[n + 1][m + 1];
for (int[] row : mem)
Arrays.fill(row, -1);
res = editDistanceDFSMem(s, t, mem, n, m);
System.out.println("변경: " + s + " → " + t + " 변경에 필요한 최소 편집 횟수: " + res + " 회");
// 동적 계획법
res = editDistanceDP(s, t);
System.out.println("변경: " + s + " → " + t + " 변경에 필요한 최소 편집 횟수: " + res + " 회");
// 공간을 최적화한 동적 계획법
res = editDistanceDPComp(s, t);
System.out.println("변경: " + s + " → " + t + " 변경에 필요한 최소 편집 횟수: " + res + " 회");
}
}

View File

@@ -0,0 +1,116 @@
/**
* File: knapsack.java
* Created Time: 2023-07-10
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class knapsack {
/* 0-1 배낭: 완전 탐색 */
static int knapsackDFS(int[] wgt, int[] val, int i, int c) {
// 모든 물건의 선택을 마쳤거나 배낭에 남은 용량이 없으면 가치 0을 반환한다
if (i == 0 || c == 0) {
return 0;
}
// 배낭 용량을 초과하면 배낭에 넣지 않는 선택만 가능하다
if (wgt[i - 1] > c) {
return knapsackDFS(wgt, val, i - 1, c);
}
// 물건 i를 넣지 않는 경우와 넣는 경우의 최대 가치를 계산한다
int no = knapsackDFS(wgt, val, i - 1, c);
int yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
// 두 경우 중 더 큰 가치를 반환한다
return Math.max(no, yes);
}
/* 0-1 배낭: 메모이제이션을 이용한 탐색 */
static int knapsackDFSMem(int[] wgt, int[] val, int[][] mem, int i, int c) {
// 모든 물건의 선택을 마쳤거나 배낭에 남은 용량이 없으면 가치 0을 반환한다
if (i == 0 || c == 0) {
return 0;
}
// 기록이 이미 있으면 바로 반환한다
if (mem[i][c] != -1) {
return mem[i][c];
}
// 배낭 용량을 초과하면 배낭에 넣지 않는 선택만 가능하다
if (wgt[i - 1] > c) {
return knapsackDFSMem(wgt, val, mem, i - 1, c);
}
// 물건 i를 넣지 않는 경우와 넣는 경우의 최대 가치를 계산한다
int no = knapsackDFSMem(wgt, val, mem, i - 1, c);
int yes = knapsackDFSMem(wgt, val, mem, i - 1, c - wgt[i - 1]) + val[i - 1];
// 두 경우 중 더 큰 가치를 기록하고 반환한다
mem[i][c] = Math.max(no, yes);
return mem[i][c];
}
/* 0-1 배낭: 동적 계획법 */
static int knapsackDP(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// dp 테이블을 초기화한다
int[][] dp = new int[n + 1][cap + 1];
// 상태 전이
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// 배낭 용량을 초과하면 물건 i를 선택하지 않는다
dp[i][c] = dp[i - 1][c];
} else {
// 물건 i를 선택하지 않는 경우와 선택하는 경우 중 더 큰 값
dp[i][c] = Math.max(dp[i - 1][c], dp[i - 1][c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[n][cap];
}
/* 0-1 배낭: 공간을 최적화한 동적 계획법 */
static int knapsackDPComp(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// dp 테이블을 초기화한다
int[] dp = new int[cap + 1];
// 상태 전이
for (int i = 1; i <= n; i++) {
// 역방향 순회
for (int c = cap; c >= 1; c--) {
if (wgt[i - 1] <= c) {
// 물건 i를 선택하지 않는 경우와 선택하는 경우 중 더 큰 값
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
public static void main(String[] args) {
int[] wgt = { 10, 20, 30, 40, 50 };
int[] val = { 50, 120, 150, 210, 240 };
int cap = 50;
int n = wgt.length;
// 완전 탐색
int res = knapsackDFS(wgt, val, n, cap);
System.out.println("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
// 메모이제이션을 이용한 탐색
int[][] mem = new int[n + 1][cap + 1];
for (int[] row : mem) {
Arrays.fill(row, -1);
}
res = knapsackDFSMem(wgt, val, mem, n, cap);
System.out.println("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
// 동적 계획법
res = knapsackDP(wgt, val, cap);
System.out.println("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
// 공간을 최적화한 동적 계획법
res = knapsackDPComp(wgt, val, cap);
System.out.println("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
}
}

View File

@@ -0,0 +1,53 @@
/**
* File: min_cost_climbing_stairs_dp.java
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class min_cost_climbing_stairs_dp {
/* 계단 오르기의 최소 비용: 동적 계획법 */
public static int minCostClimbingStairsDP(int[] cost) {
int n = cost.length - 1;
if (n == 1 || n == 2)
return cost[n];
// 부분 문제의 해를 저장할 dp 테이블을 초기화한다
int[] dp = new int[n + 1];
// 초기 상태: 가장 작은 부분 문제의 해를 미리 설정한다
dp[1] = cost[1];
dp[2] = cost[2];
// 상태 전이: 작은 부분 문제부터 점차 큰 부분 문제를 푼다
for (int i = 3; i <= n; i++) {
dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
}
return dp[n];
}
/* 계단 오르기의 최소 비용: 공간을 최적화한 동적 계획법 */
public static int minCostClimbingStairsDPComp(int[] cost) {
int n = cost.length - 1;
if (n == 1 || n == 2)
return cost[n];
int a = cost[1], b = cost[2];
for (int i = 3; i <= n; i++) {
int tmp = b;
b = Math.min(a, tmp) + cost[i];
a = tmp;
}
return b;
}
public static void main(String[] args) {
int[] cost = { 0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1 };
System.out.println(String.format("입력한 계단의 비용 리스트: %s", Arrays.toString(cost)));
int res = minCostClimbingStairsDP(cost);
System.out.println(String.format("계단을 모두 오르는 최소 비용: %d", res));
res = minCostClimbingStairsDPComp(cost);
System.out.println(String.format("계단을 모두 오르는 최소 비용: %d", res));
}
}

View File

@@ -0,0 +1,125 @@
/**
* File: min_path_sum.java
* Created Time: 2023-07-10
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
import java.util.Arrays;
public class min_path_sum {
/* 최소 경로 합: 완전 탐색 */
static int minPathSumDFS(int[][] grid, int i, int j) {
// 왼쪽 위 모서리의 칸이면 탐색을 종료한다
if (i == 0 && j == 0) {
return grid[0][0];
}
// 행 또는 열 인덱스가 범위를 벗어나면 비용 +∞를 반환한다
if (i < 0 || j < 0) {
return Integer.MAX_VALUE;
}
// 왼쪽 위 모서리에서 (i-1, j)와 (i, j-1)까지의 최소 경로 비용을 계산한다
int up = minPathSumDFS(grid, i - 1, j);
int left = minPathSumDFS(grid, i, j - 1);
// 왼쪽 위 모서리에서 (i, j)까지의 최소 경로 비용을 반환한다
return Math.min(left, up) + grid[i][j];
}
/* 최소 경로 합: 메모이제이션을 이용한 탐색 */
static int minPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) {
// 왼쪽 위 모서리의 칸이면 탐색을 종료한다
if (i == 0 && j == 0) {
return grid[0][0];
}
// 행 또는 열 인덱스가 범위를 벗어나면 비용 +∞를 반환한다
if (i < 0 || j < 0) {
return Integer.MAX_VALUE;
}
// 기록이 이미 있으면 바로 반환한다
if (mem[i][j] != -1) {
return mem[i][j];
}
// 왼쪽 칸과 위쪽 칸까지의 최소 경로 비용
int up = minPathSumDFSMem(grid, mem, i - 1, j);
int left = minPathSumDFSMem(grid, mem, i, j - 1);
// 왼쪽 위 모서리에서 (i, j)까지의 최소 경로 비용을 기록하고 반환한다
mem[i][j] = Math.min(left, up) + grid[i][j];
return mem[i][j];
}
/* 최소 경로 합: 동적 계획법 */
static int minPathSumDP(int[][] grid) {
int n = grid.length, m = grid[0].length;
// dp 테이블을 초기화한다
int[][] dp = new int[n][m];
dp[0][0] = grid[0][0];
// 상태 전이: 첫 번째 행
for (int j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// 상태 전이: 첫 번째 열
for (int i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// 상태 전이: 나머지 행과 열
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
return dp[n - 1][m - 1];
}
/* 최소 경로 합: 공간을 최적화한 동적 계획법 */
static int minPathSumDPComp(int[][] grid) {
int n = grid.length, m = grid[0].length;
// dp 테이블을 초기화한다
int[] dp = new int[m];
// 상태 전이: 첫 번째 행
dp[0] = grid[0][0];
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// 상태 전이: 나머지 행
for (int i = 1; i < n; i++) {
// 상태 전이: 첫 번째 열
dp[0] = dp[0] + grid[i][0];
// 상태 전이: 나머지 열
for (int j = 1; j < m; j++) {
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
public static void main(String[] args) {
int[][] grid = {
{ 1, 3, 1, 5 },
{ 2, 2, 4, 2 },
{ 5, 3, 2, 1 },
{ 4, 3, 5, 2 }
};
int n = grid.length, m = grid[0].length;
// 완전 탐색
int res = minPathSumDFS(grid, n - 1, m - 1);
System.out.println("왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: " + res);
// 메모이제이션을 이용한 탐색
int[][] mem = new int[n][m];
for (int[] row : mem) {
Arrays.fill(row, -1);
}
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
System.out.println("왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: " + res);
// 동적 계획법
res = minPathSumDP(grid);
System.out.println("왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: " + res);
// 공간을 최적화한 동적 계획법
res = minPathSumDPComp(grid);
System.out.println("왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: " + res);
}
}

View File

@@ -0,0 +1,63 @@
/**
* File: unbounded_knapsack.java
* Created Time: 2023-07-11
* Author: krahets (krahets@163.com)
*/
package chapter_dynamic_programming;
public class unbounded_knapsack {
/* 무한 배낭: 동적 계획법 */
static int unboundedKnapsackDP(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// dp 테이블을 초기화한다
int[][] dp = new int[n + 1][cap + 1];
// 상태 전이
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// 배낭 용량을 초과하면 물건 i를 선택하지 않는다
dp[i][c] = dp[i - 1][c];
} else {
// 물건 i를 선택하지 않는 경우와 선택하는 경우 중 더 큰 값
dp[i][c] = Math.max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[n][cap];
}
/* 무한 배낭: 공간을 최적화한 동적 계획법 */
static int unboundedKnapsackDPComp(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// dp 테이블을 초기화한다
int[] dp = new int[cap + 1];
// 상태 전이
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// 배낭 용량을 초과하면 물건 i를 선택하지 않는다
dp[c] = dp[c];
} else {
// 물건 i를 선택하지 않는 경우와 선택하는 경우 중 더 큰 값
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
public static void main(String[] args) {
int[] wgt = { 1, 2, 3 };
int[] val = { 5, 11, 15 };
int cap = 4;
// 동적 계획법
int res = unboundedKnapsackDP(wgt, val, cap);
System.out.println("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
// 공간을 최적화한 동적 계획법
res = unboundedKnapsackDPComp(wgt, val, cap);
System.out.println("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
}
}

View File

@@ -0,0 +1,117 @@
/**
* File: graph_adjacency_list.java
* Created Time: 2023-01-26
* Author: krahets (krahets@163.com)
*/
package chapter_graph;
import java.util.*;
import utils.*;
/* 인접 리스트로 구현한 무방향 그래프 클래스 */
class GraphAdjList {
// 인접 리스트의 key: 정점, value: 해당 정점의 모든 인접 정점
Map<Vertex, List<Vertex>> adjList;
/* 생성자 */
public GraphAdjList(Vertex[][] edges) {
this.adjList = new HashMap<>();
// 모든 정점과 간선을 추가한다
for (Vertex[] edge : edges) {
addVertex(edge[0]);
addVertex(edge[1]);
addEdge(edge[0], edge[1]);
}
}
/* 정점 개수 반환 */
public int size() {
return adjList.size();
}
/* 간선 추가 */
public void addEdge(Vertex vet1, Vertex vet2) {
if (!adjList.containsKey(vet1) || !adjList.containsKey(vet2) || vet1 == vet2)
throw new IllegalArgumentException();
// 간선 vet1 - vet2를 추가한다
adjList.get(vet1).add(vet2);
adjList.get(vet2).add(vet1);
}
/* 간선 삭제 */
public void removeEdge(Vertex vet1, Vertex vet2) {
if (!adjList.containsKey(vet1) || !adjList.containsKey(vet2) || vet1 == vet2)
throw new IllegalArgumentException();
// 간선 vet1 - vet2를 삭제한다
adjList.get(vet1).remove(vet2);
adjList.get(vet2).remove(vet1);
}
/* 정점 추가 */
public void addVertex(Vertex vet) {
if (adjList.containsKey(vet))
return;
// 인접 리스트에 새 연결 리스트를 추가한다
adjList.put(vet, new ArrayList<>());
}
/* 정점 삭제 */
public void removeVertex(Vertex vet) {
if (!adjList.containsKey(vet))
throw new IllegalArgumentException();
// 인접 리스트에서 정점 vet에 해당하는 연결 리스트를 삭제한다
adjList.remove(vet);
// 다른 정점의 연결 리스트를 순회하여 vet를 포함하는 모든 간선을 삭제한다
for (List<Vertex> list : adjList.values()) {
list.remove(vet);
}
}
/* 인접 리스트 출력 */
public void print() {
System.out.println("인접 리스트 =");
for (Map.Entry<Vertex, List<Vertex>> pair : adjList.entrySet()) {
List<Integer> tmp = new ArrayList<>();
for (Vertex vertex : pair.getValue())
tmp.add(vertex.val);
System.out.println(pair.getKey().val + ": " + tmp + ",");
}
}
}
public class graph_adjacency_list {
public static void main(String[] args) {
/* 무방향 그래프 초기화 */
Vertex[] v = Vertex.valsToVets(new int[] { 1, 3, 2, 5, 4 });
Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] },
{ v[2], v[3] }, { v[2], v[4] }, { v[3], v[4] } };
GraphAdjList graph = new GraphAdjList(edges);
System.out.println("\n초기화한 후의 그래프");
graph.print();
/* 간선 추가 */
// 정점 1, 2는 각각 v[0], v[2]이다
graph.addEdge(v[0], v[2]);
System.out.println("\n간선 1-2를 추가한 후의 그래프");
graph.print();
/* 간선 삭제 */
// 정점 1, 3은 각각 v[0], v[1]이다
graph.removeEdge(v[0], v[1]);
System.out.println("\n간선 1-3을 삭제한 후의 그래프");
graph.print();
/* 정점 추가 */
Vertex v5 = new Vertex(6);
graph.addVertex(v5);
System.out.println("\n정점 6을 추가한 후의 그래프");
graph.print();
/* 정점 삭제 */
// 정점 3은 v[1]이다
graph.removeVertex(v[1]);
System.out.println("\n정점 3을 삭제한 후의 그래프");
graph.print();
}
}

View File

@@ -0,0 +1,131 @@
/**
* File: graph_adjacency_matrix.java
* Created Time: 2023-01-26
* Author: krahets (krahets@163.com)
*/
package chapter_graph;
import utils.*;
import java.util.*;
/* 인접 행렬로 구현한 무방향 그래프 클래스 */
class GraphAdjMat {
List<Integer> vertices; // 정점 리스트의 원소는 정점 값을, 인덱스는 정점 인덱스를 나타낸다
List<List<Integer>> adjMat; // 인접 행렬의 행과 열 인덱스는 정점 인덱스에 해당한다
/* 생성자 */
public GraphAdjMat(int[] vertices, int[][] edges) {
this.vertices = new ArrayList<>();
this.adjMat = new ArrayList<>();
// 정점 추가
for (int val : vertices) {
addVertex(val);
}
// 간선 추가
// edges의 원소는 정점 인덱스, 즉 vertices 원소의 인덱스를 나타낸다
for (int[] e : edges) {
addEdge(e[0], e[1]);
}
}
/* 정점 개수 반환 */
public int size() {
return vertices.size();
}
/* 정점 추가 */
public void addVertex(int val) {
int n = size();
// 정점 리스트에 새 정점의 값을 추가한다
vertices.add(val);
// 인접 행렬에 행 하나를 추가한다
List<Integer> newRow = new ArrayList<>(n);
for (int j = 0; j < n; j++) {
newRow.add(0);
}
adjMat.add(newRow);
// 인접 행렬에 열 하나를 추가한다
for (List<Integer> row : adjMat) {
row.add(0);
}
}
/* 정점 삭제 */
public void removeVertex(int index) {
if (index >= size())
throw new IndexOutOfBoundsException();
// 정점 리스트에서 인덱스 index의 정점을 제거한다
vertices.remove(index);
// 인접 행렬에서 인덱스 index의 행을 삭제한다
adjMat.remove(index);
// 인접 행렬에서 인덱스 index의 열을 삭제한다
for (List<Integer> row : adjMat) {
row.remove(index);
}
}
/* 간선 추가 */
// 매개변수 i, j는 vertices 원소의 인덱스에 해당한다
public void addEdge(int i, int j) {
// 인덱스가 범위를 벗어나거나 서로 같은 경우를 처리한다
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j)
throw new IndexOutOfBoundsException();
// 무방향 그래프의 인접 행렬은 주대각선에 대해 대칭이며, (i, j) == (j, i)를 만족한다
adjMat.get(i).set(j, 1);
adjMat.get(j).set(i, 1);
}
/* 간선 삭제 */
// 매개변수 i, j는 vertices 원소의 인덱스에 해당한다
public void removeEdge(int i, int j) {
// 인덱스가 범위를 벗어나거나 서로 같은 경우를 처리한다
if (i < 0 || j < 0 || i >= size() || j >= size() || i == j)
throw new IndexOutOfBoundsException();
adjMat.get(i).set(j, 0);
adjMat.get(j).set(i, 0);
}
/* 인접 행렬 출력 */
public void print() {
System.out.print("정점 리스트 = ");
System.out.println(vertices);
System.out.println("인접 행렬 =");
PrintUtil.printMatrix(adjMat);
}
}
public class graph_adjacency_matrix {
public static void main(String[] args) {
/* 무방향 그래프 초기화 */
// edges의 원소는 정점 인덱스, 즉 vertices 원소의 인덱스를 나타낸다
int[] vertices = { 1, 3, 2, 5, 4 };
int[][] edges = { { 0, 1 }, { 0, 3 }, { 1, 2 }, { 2, 3 }, { 2, 4 }, { 3, 4 } };
GraphAdjMat graph = new GraphAdjMat(vertices, edges);
System.out.println("\n초기화한 후의 그래프");
graph.print();
/* 간선 추가 */
// 정점 1, 2의 인덱스는 각각 0, 2이다
graph.addEdge(0, 2);
System.out.println("\n간선 1-2를 추가한 후의 그래프");
graph.print();
/* 간선 삭제 */
// 정점 1, 3의 인덱스는 각각 0, 1이다
graph.removeEdge(0, 1);
System.out.println("\n간선 1-3을 삭제한 후의 그래프");
graph.print();
/* 정점 추가 */
graph.addVertex(6);
System.out.println("\n정점 6을 추가한 후의 그래프");
graph.print();
/* 정점 삭제 */
// 정점 3의 인덱스는 1이다
graph.removeVertex(1);
System.out.println("\n정점 3을 삭제한 후의 그래프");
graph.print();
}
}

View File

@@ -0,0 +1,55 @@
/**
* File: graph_bfs.java
* Created Time: 2023-02-12
* Author: krahets (krahets@163.com)
*/
package chapter_graph;
import java.util.*;
import utils.*;
public class graph_bfs {
/* 너비 우선 순회 */
// 지정한 정점의 모든 인접 정점을 얻기 쉽도록 그래프를 인접 리스트로 표현한다
static List<Vertex> graphBFS(GraphAdjList graph, Vertex startVet) {
// 정점 순회 순서
List<Vertex> res = new ArrayList<>();
// 방문한 정점을 기록하는 해시 집합
Set<Vertex> visited = new HashSet<>();
visited.add(startVet);
// 큐를 사용하여 BFS를 구현한다
Queue<Vertex> que = new LinkedList<>();
que.offer(startVet);
// 정점 vet에서 시작하여 모든 정점을 방문할 때까지 반복한다
while (!que.isEmpty()) {
Vertex vet = que.poll(); // 큐 맨 앞의 정점을 꺼낸다
res.add(vet); // 방문한 정점을 기록한다
// 해당 정점의 모든 인접 정점을 순회한다
for (Vertex adjVet : graph.adjList.get(vet)) {
if (visited.contains(adjVet))
continue; // 이미 방문한 정점은 건너뛴다
que.offer(adjVet); // 방문하지 않은 정점만 큐에 삽입한다
visited.add(adjVet); // 해당 정점을 방문했다고 표시한다
}
}
// 정점 순회 순서를 반환한다
return res;
}
public static void main(String[] args) {
/* 무방향 그래프 초기화 */
Vertex[] v = Vertex.valsToVets(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] }, { v[1], v[4] },
{ v[2], v[5] }, { v[3], v[4] }, { v[3], v[6] }, { v[4], v[5] },
{ v[4], v[7] }, { v[5], v[8] }, { v[6], v[7] }, { v[7], v[8] } };
GraphAdjList graph = new GraphAdjList(edges);
System.out.println("\n초기화한 후의 그래프");
graph.print();
/* 너비 우선 순회 */
List<Vertex> res = graphBFS(graph, v[0]);
System.out.println("\n너비 우선 순회(BFS)의 정점 순서");
System.out.println(Vertex.vetsToVals(res));
}
}

View File

@@ -0,0 +1,51 @@
/**
* File: graph_dfs.java
* Created Time: 2023-02-12
* Author: krahets (krahets@163.com)
*/
package chapter_graph;
import java.util.*;
import utils.*;
public class graph_dfs {
/* 깊이 우선 순회 보조 함수 */
static void dfs(GraphAdjList graph, Set<Vertex> visited, List<Vertex> res, Vertex vet) {
res.add(vet); // 방문한 정점을 기록한다
visited.add(vet); // 해당 정점을 방문했다고 표시한다
// 해당 정점의 모든 인접 정점을 순회한다
for (Vertex adjVet : graph.adjList.get(vet)) {
if (visited.contains(adjVet))
continue; // 이미 방문한 정점은 건너뛴다
// 인접 정점을 재귀적으로 방문한다
dfs(graph, visited, res, adjVet);
}
}
/* 깊이 우선 순회 */
// 지정한 정점의 모든 인접 정점을 얻기 쉽도록 그래프를 인접 리스트로 표현한다
static List<Vertex> graphDFS(GraphAdjList graph, Vertex startVet) {
// 정점 순회 순서
List<Vertex> res = new ArrayList<>();
// 방문한 정점을 기록하는 해시 집합
Set<Vertex> visited = new HashSet<>();
dfs(graph, visited, res, startVet);
return res;
}
public static void main(String[] args) {
/* 무방향 그래프 초기화 */
Vertex[] v = Vertex.valsToVets(new int[] { 0, 1, 2, 3, 4, 5, 6 });
Vertex[][] edges = { { v[0], v[1] }, { v[0], v[3] }, { v[1], v[2] },
{ v[2], v[5] }, { v[4], v[5] }, { v[5], v[6] } };
GraphAdjList graph = new GraphAdjList(edges);
System.out.println("\n초기화한 후의 그래프");
graph.print();
/* 깊이 우선 순회 */
List<Vertex> res = graphDFS(graph, v[0]);
System.out.println("\n깊이 우선 순회(DFS)의 정점 순서");
System.out.println(Vertex.vetsToVals(res));
}
}

View File

@@ -0,0 +1,55 @@
/**
* File: coin_change_greedy.java
* Created Time: 2023-07-20
* Author: krahets (krahets@163.com)
*/
package chapter_greedy;
import java.util.Arrays;
public class coin_change_greedy {
/* 동전 교환: 탐욕 */
static int coinChangeGreedy(int[] coins, int amt) {
// coins 리스트가 정렬되어 있다고 가정한다
int i = coins.length - 1;
int count = 0;
// 남은 금액이 없을 때까지 탐욕적 선택을 반복한다
while (amt > 0) {
// 남은 금액보다 작으면서 가장 가까운 금액의 동전을 찾는다
while (i > 0 && coins[i] > amt) {
i--;
}
// coins[i]를 선택한다
amt -= coins[i];
count++;
}
// 가능한 방법을 찾지 못하면 -1을 반환한다
return amt == 0 ? count : -1;
}
public static void main(String[] args) {
// 탐욕: 전역 최적해를 찾는 것이 보장된다
int[] coins = { 1, 5, 10, 20, 50, 100 };
int amt = 186;
int res = coinChangeGreedy(coins, amt);
System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt);
System.out.println("목표 금액: " + amt + " ; 필요한 최소 동전 개수: " + res);
// 탐욕: 전역 최적해를 찾는 것이 보장되지 않는다
coins = new int[] { 1, 20, 50 };
amt = 60;
res = coinChangeGreedy(coins, amt);
System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt);
System.out.println("목표 금액: " + amt + " ; 필요한 최소 동전 개수: " + res);
System.out.println("실제로 필요한 최소 개수는 3개이며, 20 + 20 + 20이다");
// 탐욕: 전역 최적해를 찾는 것이 보장되지 않는다
coins = new int[] { 1, 49, 50 };
amt = 98;
res = coinChangeGreedy(coins, amt);
System.out.println("\ncoins = " + Arrays.toString(coins) + ", amt = " + amt);
System.out.println("목표 금액: " + amt + " ; 필요한 최소 동전 개수: " + res);
System.out.println("실제로 필요한 최소 개수는 2개이며, 49 + 49이다");
}
}

View File

@@ -0,0 +1,59 @@
/**
* File: fractional_knapsack.java
* Created Time: 2023-07-20
* Author: krahets (krahets@163.com)
*/
package chapter_greedy;
import java.util.Arrays;
import java.util.Comparator;
/* 물건 */
class Item {
int w; // 물건의 무게
int v; // 물건의 가치
public Item(int w, int v) {
this.w = w;
this.v = v;
}
}
public class fractional_knapsack {
/* 분할 가능한 배낭: 탐욕 */
static double fractionalKnapsack(int[] wgt, int[] val, int cap) {
// 무게와 가치 두 속성을 갖는 물건의 리스트를 생성한다
Item[] items = new Item[wgt.length];
for (int i = 0; i < wgt.length; i++) {
items[i] = new Item(wgt[i], val[i]);
}
// 단위 가치 item.v / item.w를 기준으로 내림차순 정렬한다
Arrays.sort(items, Comparator.comparingDouble(item -> -((double) item.v / item.w)));
// 탐욕적 선택을 반복한다
double res = 0;
for (Item item : items) {
if (item.w <= cap) {
// 남은 용량이 충분하면 현재 물건을 통째로 배낭에 넣는다
res += item.v;
cap -= item.w;
} else {
// 남은 용량이 부족하면 현재 물건의 일부를 배낭에 넣는다
res += (double) item.v / item.w * cap;
// 남은 용량이 없으므로 반복문을 종료한다
break;
}
}
return res;
}
public static void main(String[] args) {
int[] wgt = { 10, 20, 30, 40, 50 };
int[] val = { 50, 120, 150, 210, 240 };
int cap = 50;
// 탐욕 알고리즘
double res = fractionalKnapsack(wgt, val, cap);
System.out.println("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
}
}

View File

@@ -0,0 +1,38 @@
/**
* File: max_capacity.java
* Created Time: 2023-07-21
* Author: krahets (krahets@163.com)
*/
package chapter_greedy;
public class max_capacity {
/* 최대 용량: 탐욕 */
static int maxCapacity(int[] ht) {
// i와 j가 각각 배열의 양 끝을 가리키도록 초기화한다
int i = 0, j = ht.length - 1;
// 최대 용량의 초깃값은 0이다
int res = 0;
// 두 칸막이가 만날 때까지 탐욕적 선택을 반복한다
while (i < j) {
// 최대 용량을 갱신한다
int cap = Math.min(ht[i], ht[j]) * (j - i);
res = Math.max(res, cap);
// 낮은 칸막이를 안쪽으로 이동한다
if (ht[i] < ht[j]) {
i++;
} else {
j--;
}
}
return res;
}
public static void main(String[] args) {
int[] ht = { 3, 8, 5, 2, 7, 7, 3, 4 };
// 탐욕 알고리즘
int res = maxCapacity(ht);
System.out.println("최대 용량: " + res);
}
}

View File

@@ -0,0 +1,40 @@
/**
* File: max_product_cutting.java
* Created Time: 2023-07-21
* Author: krahets (krahets@163.com)
*/
package chapter_greedy;
import java.lang.Math;
public class max_product_cutting {
/* 분할 후의 최대 곱: 탐욕 */
public static int maxProductCutting(int n) {
// n <= 3이면 반드시 1 하나가 나오도록 분할해야 한다
if (n <= 3) {
return 1 * (n - 1);
}
// 탐욕적으로 3을 떼어 낸다. a는 3의 개수이고 b는 나머지이다
int a = n / 3;
int b = n % 3;
if (b == 1) {
// 나머지가 1이면 1 * 3 한 쌍을 2 * 2로 바꾼다
return (int) Math.pow(3, a - 1) * 2 * 2;
}
if (b == 2) {
// 나머지가 2이면 별도로 처리하지 않는다
return (int) Math.pow(3, a) * 2;
}
// 나머지가 0이면 별도로 처리하지 않는다
return (int) Math.pow(3, a);
}
public static void main(String[] args) {
int n = 58;
// 탐욕 알고리즘
int res = maxProductCutting(n);
System.out.println("분할 후의 최대 곱: " + res);
}
}

View File

@@ -0,0 +1,141 @@
/**
* File: array_hash_map.java
* Created Time: 2022-12-04
* Author: krahets (krahets@163.com)
*/
package chapter_hashing;
import java.util.*;
/* 키-값 쌍 */
class Pair {
public int key;
public String val;
public Pair(int key, String val) {
this.key = key;
this.val = val;
}
}
/* 배열로 구현한 해시 테이블 */
class ArrayHashMap {
private List<Pair> buckets;
public ArrayHashMap() {
// 버킷 100개를 포함하는 배열을 초기화한다
buckets = new ArrayList<>();
for (int i = 0; i < 100; i++) {
buckets.add(null);
}
}
/* 해시 함수 */
private int hashFunc(int key) {
int index = key % 100;
return index;
}
/* 조회 연산 */
public String get(int key) {
int index = hashFunc(key);
Pair pair = buckets.get(index);
if (pair == null)
return null;
return pair.val;
}
/* 추가 연산 */
public void put(int key, String val) {
Pair pair = new Pair(key, val);
int index = hashFunc(key);
buckets.set(index, pair);
}
/* 삭제 연산 */
public void remove(int key) {
int index = hashFunc(key);
// null로 설정하여 삭제를 나타낸다
buckets.set(index, null);
}
/* 모든 키-값 쌍 반환 */
public List<Pair> pairSet() {
List<Pair> pairSet = new ArrayList<>();
for (Pair pair : buckets) {
if (pair != null)
pairSet.add(pair);
}
return pairSet;
}
/* 모든 키 반환 */
public List<Integer> keySet() {
List<Integer> keySet = new ArrayList<>();
for (Pair pair : buckets) {
if (pair != null)
keySet.add(pair.key);
}
return keySet;
}
/* 모든 값 반환 */
public List<String> valueSet() {
List<String> valueSet = new ArrayList<>();
for (Pair pair : buckets) {
if (pair != null)
valueSet.add(pair.val);
}
return valueSet;
}
/* 해시 테이블 출력 */
public void print() {
for (Pair kv : pairSet()) {
System.out.println(kv.key + " -> " + kv.val);
}
}
}
public class array_hash_map {
public static void main(String[] args) {
/* 해시 테이블 초기화 */
ArrayHashMap map = new ArrayHashMap();
/* 추가 연산 */
// 해시 테이블에 (key, value) 키-값 쌍을 추가한다
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
System.out.println("\n추가를 마친 후의 해시 테이블\n키 -> 값");
map.print();
/* 조회 연산 */
// 해시 테이블에 키 key를 입력하여 값 value를 얻는다
String name = map.get(15937);
System.out.println("\n학번 15937을 입력하여 조회한 이름 " + name);
/* 삭제 연산 */
// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다
map.remove(10583);
System.out.println("\n10583을 삭제한 후의 해시 테이블\n키 -> 값");
map.print();
/* 해시 테이블 순회 */
System.out.println("\n키-값 쌍(키->값) 순회");
for (Pair kv : map.pairSet()) {
System.out.println(kv.key + " -> " + kv.val);
}
System.out.println("\n키 Key만 순회");
for (int key : map.keySet()) {
System.out.println(key);
}
System.out.println("\n값 Value만 순회");
for (String val : map.valueSet()) {
System.out.println(val);
}
}
}

View File

@@ -0,0 +1,38 @@
/**
* File: built_in_hash.java
* Created Time: 2023-06-21
* Author: krahets (krahets@163.com)
*/
package chapter_hashing;
import utils.*;
import java.util.*;
public class built_in_hash {
public static void main(String[] args) {
int num = 3;
int hashNum = Integer.hashCode(num);
System.out.println("정수 " + num + " ; 해시값: " + hashNum);
boolean bol = true;
int hashBol = Boolean.hashCode(bol);
System.out.println("불리언 값 " + bol + " ; 해시값: " + hashBol);
double dec = 3.14159;
int hashDec = Double.hashCode(dec);
System.out.println("소수 " + dec + " ; 해시값: " + hashDec);
String str = "Hello 算法";
int hashStr = str.hashCode();
System.out.println("문자열 " + str + " ; 해시값: " + hashStr);
Object[] arr = { 12836, "小哈" };
int hashTup = Arrays.hashCode(arr);
System.out.println("배열 " + Arrays.toString(arr) + " ; 해시값: " + hashTup);
ListNode obj = new ListNode(0);
int hashObj = obj.hashCode();
System.out.println("노드 객체 " + obj + " ; 해시값: " + hashObj);
}
}

View File

@@ -0,0 +1,52 @@
/**
* File: hash_map.java
* Created Time: 2022-12-04
* Author: krahets (krahets@163.com)
*/
package chapter_hashing;
import java.util.*;
import utils.*;
public class hash_map {
public static void main(String[] args) {
/* 해시 테이블 초기화 */
Map<Integer, String> map = new HashMap<>();
/* 추가 연산 */
// 해시 테이블에 (key, value) 키-값 쌍을 추가한다
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
System.out.println("\n추가를 마친 후의 해시 테이블\n키 -> 값");
PrintUtil.printHashMap(map);
/* 조회 연산 */
// 해시 테이블에 키 key를 입력하여 값 value를 얻는다
String name = map.get(15937);
System.out.println("\n학번 15937을 입력하여 조회한 이름 " + name);
/* 삭제 연산 */
// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다
map.remove(10583);
System.out.println("\n10583을 삭제한 후의 해시 테이블\n키 -> 값");
PrintUtil.printHashMap(map);
/* 해시 테이블 순회 */
System.out.println("\n키-값 쌍(키->값) 순회");
for (Map.Entry<Integer, String> kv : map.entrySet()) {
System.out.println(kv.getKey() + " -> " + kv.getValue());
}
System.out.println("\n키 Key만 순회");
for (int key : map.keySet()) {
System.out.println(key);
}
System.out.println("\n값 Value만 순회");
for (String val : map.values()) {
System.out.println(val);
}
}
}

View File

@@ -0,0 +1,148 @@
/**
* File: hash_map_chaining.java
* Created Time: 2023-06-13
* Author: krahets (krahets@163.com)
*/
package chapter_hashing;
import java.util.ArrayList;
import java.util.List;
/* 체이닝 해시 테이블 */
class HashMapChaining {
int size; // 키-값 쌍 개수
int capacity; // 해시 테이블 용량
double loadThres; // 용량 확장을 수행하는 적재율 임계값
int extendRatio; // 용량 확장 배수
List<List<Pair>> buckets; // 버킷 배열
/* 생성자 */
public HashMapChaining() {
size = 0;
capacity = 4;
loadThres = 2.0 / 3.0;
extendRatio = 2;
buckets = new ArrayList<>(capacity);
for (int i = 0; i < capacity; i++) {
buckets.add(new ArrayList<>());
}
}
/* 해시 함수 */
int hashFunc(int key) {
return key % capacity;
}
/* 적재율 */
double loadFactor() {
return (double) size / capacity;
}
/* 조회 연산 */
String get(int key) {
int index = hashFunc(key);
List<Pair> bucket = buckets.get(index);
// 버킷을 순회하다 key를 찾으면 해당 val을 반환한다
for (Pair pair : bucket) {
if (pair.key == key) {
return pair.val;
}
}
// key를 찾지 못하면 null을 반환한다
return null;
}
/* 추가 연산 */
void put(int key, String val) {
// 적재율이 임계값을 초과하면 용량을 확장한다
if (loadFactor() > loadThres) {
extend();
}
int index = hashFunc(key);
List<Pair> bucket = buckets.get(index);
// 버킷을 순회하다 지정한 key를 만나면 해당 val을 갱신하고 반환한다
for (Pair pair : bucket) {
if (pair.key == key) {
pair.val = val;
return;
}
}
// 해당 key가 없으면 키-값 쌍을 맨 뒤에 추가한다
Pair pair = new Pair(key, val);
bucket.add(pair);
size++;
}
/* 삭제 연산 */
void remove(int key) {
int index = hashFunc(key);
List<Pair> bucket = buckets.get(index);
// 버킷을 순회하며 키-값 쌍을 삭제한다
for (Pair pair : bucket) {
if (pair.key == key) {
bucket.remove(pair);
size--;
break;
}
}
}
/* 해시 테이블 용량 확장 */
void extend() {
// 원래 해시 테이블을 임시로 저장한다
List<List<Pair>> bucketsTmp = buckets;
// 용량을 확장한 새 해시 테이블을 초기화한다
capacity *= extendRatio;
buckets = new ArrayList<>(capacity);
for (int i = 0; i < capacity; i++) {
buckets.add(new ArrayList<>());
}
size = 0;
// 원래 해시 테이블의 키-값 쌍을 새 해시 테이블로 옮긴다
for (List<Pair> bucket : bucketsTmp) {
for (Pair pair : bucket) {
put(pair.key, pair.val);
}
}
}
/* 해시 테이블 출력 */
void print() {
for (List<Pair> bucket : buckets) {
List<String> res = new ArrayList<>();
for (Pair pair : bucket) {
res.add(pair.key + " -> " + pair.val);
}
System.out.println(res);
}
}
}
public class hash_map_chaining {
public static void main(String[] args) {
/* 해시 테이블 초기화 */
HashMapChaining map = new HashMapChaining();
/* 추가 연산 */
// 해시 테이블에 (key, value) 키-값 쌍을 추가한다
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
System.out.println("\n추가를 마친 후의 해시 테이블\n키 -> 값");
map.print();
/* 조회 연산 */
// 해시 테이블에 키 key를 입력하여 값 value를 얻는다
String name = map.get(13276);
System.out.println("\n학번 13276을 입력하여 조회한 이름 " + name);
/* 삭제 연산 */
// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다
map.remove(12836);
System.out.println("\n12836을 삭제한 뒤의 해시 테이블\n키 -> 값");
map.print();
}
}

View File

@@ -0,0 +1,158 @@
/**
* File: hash_map_open_addressing.java
* Created Time: 2023-06-13
* Author: krahets (krahets@163.com)
*/
package chapter_hashing;
/* 개방 주소법 해시 테이블 */
class HashMapOpenAddressing {
private int size; // 키-값 쌍 개수
private int capacity = 4; // 해시 테이블 용량
private final double loadThres = 2.0 / 3.0; // 용량 확장을 수행하는 적재율 임계값
private final int extendRatio = 2; // 용량 확장 배수
private Pair[] buckets; // 버킷 배열
private final Pair TOMBSTONE = new Pair(-1, "-1"); // 삭제 표시
/* 생성자 */
public HashMapOpenAddressing() {
size = 0;
buckets = new Pair[capacity];
}
/* 해시 함수 */
private int hashFunc(int key) {
return key % capacity;
}
/* 적재율 */
private double loadFactor() {
return (double) size / capacity;
}
/* key에 해당하는 버킷 인덱스 탐색 */
private int findBucket(int key) {
int index = hashFunc(key);
int firstTombstone = -1;
// 선형 탐사로 탐색하고, 빈 버킷을 만나면 반복문을 종료한다
while (buckets[index] != null) {
// key를 만나면 해당 버킷 인덱스를 반환한다
if (buckets[index].key == key) {
// 이전에 삭제 표시를 만났으면 키-값 쌍을 그 인덱스로 옮긴다
if (firstTombstone != -1) {
buckets[firstTombstone] = buckets[index];
buckets[index] = TOMBSTONE;
return firstTombstone; // 옮긴 후의 버킷 인덱스를 반환한다
}
return index; // 버킷 인덱스를 반환한다
}
// 처음 만난 삭제 표시를 기록한다
if (firstTombstone == -1 && buckets[index] == TOMBSTONE) {
firstTombstone = index;
}
// 버킷 인덱스를 계산하고, 끝을 넘어가면 처음으로 돌아온다
index = (index + 1) % capacity;
}
// key가 없으면 추가할 위치의 인덱스를 반환한다
return firstTombstone == -1 ? index : firstTombstone;
}
/* 조회 연산 */
public String get(int key) {
// key에 해당하는 버킷 인덱스 탐색
int index = findBucket(key);
// 키-값 쌍을 찾으면 해당 val을 반환한다
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
return buckets[index].val;
}
// 키-값 쌍이 없으면 null을 반환한다
return null;
}
/* 추가 연산 */
public void put(int key, String val) {
// 적재율이 임계값을 초과하면 용량을 확장한다
if (loadFactor() > loadThres) {
extend();
}
// key에 해당하는 버킷 인덱스 탐색
int index = findBucket(key);
// 키-값 쌍을 찾으면 val을 덮어쓰고 반환한다
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
buckets[index].val = val;
return;
}
// 키-값 쌍이 없으면 해당 키-값 쌍을 추가한다
buckets[index] = new Pair(key, val);
size++;
}
/* 삭제 연산 */
public void remove(int key) {
// key에 해당하는 버킷 인덱스 탐색
int index = findBucket(key);
// 키-값 쌍을 찾으면 삭제 표시로 덮어쓴다
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
buckets[index] = TOMBSTONE;
size--;
}
}
/* 해시 테이블 용량 확장 */
private void extend() {
// 원래 해시 테이블을 임시로 저장한다
Pair[] bucketsTmp = buckets;
// 용량을 확장한 새 해시 테이블을 초기화한다
capacity *= extendRatio;
buckets = new Pair[capacity];
size = 0;
// 원래 해시 테이블의 키-값 쌍을 새 해시 테이블로 옮긴다
for (Pair pair : bucketsTmp) {
if (pair != null && pair != TOMBSTONE) {
put(pair.key, pair.val);
}
}
}
/* 해시 테이블 출력 */
public void print() {
for (Pair pair : buckets) {
if (pair == null) {
System.out.println("null");
} else if (pair == TOMBSTONE) {
System.out.println("TOMBSTONE");
} else {
System.out.println(pair.key + " -> " + pair.val);
}
}
}
}
public class hash_map_open_addressing {
public static void main(String[] args) {
// 해시 테이블 초기화
HashMapOpenAddressing hashmap = new HashMapOpenAddressing();
// 추가 연산
// 해시 테이블에 키-값 쌍 (key, val)을 추가한다
hashmap.put(12836, "小哈");
hashmap.put(15937, "小啰");
hashmap.put(16750, "小算");
hashmap.put(13276, "小法");
hashmap.put(10583, "小鸭");
System.out.println("\n추가를 마친 후의 해시 테이블\n키 -> 값");
hashmap.print();
// 조회 연산
// 해시 테이블에 키 key를 입력하여 값 val을 얻는다
String name = hashmap.get(13276);
System.out.println("\n학번 13276을 입력하여 조회한 이름 " + name);
// 삭제 연산
// 해시 테이블에서 키-값 쌍 (key, val)을 삭제한다
hashmap.remove(16750);
System.out.println("\n16750을 삭제한 후의 해시 테이블\n키 -> 값");
hashmap.print();
}
}

View File

@@ -0,0 +1,65 @@
/**
* File: simple_hash.java
* Created Time: 2023-06-21
* Author: krahets (krahets@163.com)
*/
package chapter_hashing;
public class simple_hash {
/* 덧셈 해시 */
static int addHash(String key) {
long hash = 0;
final int MODULUS = 1000000007;
for (char c : key.toCharArray()) {
hash = (hash + (int) c) % MODULUS;
}
return (int) hash;
}
/* 곱셈 해시 */
static int mulHash(String key) {
long hash = 0;
final int MODULUS = 1000000007;
for (char c : key.toCharArray()) {
hash = (31 * hash + (int) c) % MODULUS;
}
return (int) hash;
}
/* XOR 해시 */
static int xorHash(String key) {
int hash = 0;
final int MODULUS = 1000000007;
for (char c : key.toCharArray()) {
hash ^= (int) c;
}
return hash & MODULUS;
}
/* 회전 해시 */
static int rotHash(String key) {
long hash = 0;
final int MODULUS = 1000000007;
for (char c : key.toCharArray()) {
hash = ((hash << 4) ^ (hash >> 28) ^ (int) c) % MODULUS;
}
return (int) hash;
}
public static void main(String[] args) {
String key = "Hello 算法";
int hash = addHash(key);
System.out.println("덧셈 해시값: " + hash);
hash = mulHash(key);
System.out.println("곱셈 해시값: " + hash);
hash = xorHash(key);
System.out.println("XOR 해시값: " + hash);
hash = rotHash(key);
System.out.println("회전 해시값: " + hash);
}
}

View File

@@ -0,0 +1,66 @@
/**
* File: heap.java
* Created Time: 2023-01-07
* Author: krahets (krahets@163.com)
*/
package chapter_heap;
import utils.*;
import java.util.*;
public class heap {
public static void testPush(Queue<Integer> heap, int val) {
heap.offer(val); // 힙에 원소 삽입
System.out.format("\n원소를 힙에 삽입한 후(원소: %d)\n", val);
PrintUtil.printHeap(heap);
}
public static void testPop(Queue<Integer> heap) {
int val = heap.poll(); // 힙의 루트 원소 꺼내기
System.out.format("\n힙의 루트 원소를 꺼낸 후(원소: %d)\n", val);
PrintUtil.printHeap(heap);
}
public static void main(String[] args) {
/* 힙 초기화 */
// 최소 힙 초기화
Queue<Integer> minHeap = new PriorityQueue<>();
// 최대 힙 초기화(lambda 식으로 Comparator를 수정하면 된다)
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
System.out.println("\n다음 테스트 예제는 최대 힙이다");
/* 힙에 원소 삽입 */
testPush(maxHeap, 1);
testPush(maxHeap, 3);
testPush(maxHeap, 2);
testPush(maxHeap, 5);
testPush(maxHeap, 4);
/* 힙의 루트 원소 반환 */
int peek = maxHeap.peek();
System.out.format("\n힙의 루트 원소: %d\n", peek);
/* 힙의 루트 원소 꺼내기 */
testPop(maxHeap);
testPop(maxHeap);
testPop(maxHeap);
testPop(maxHeap);
testPop(maxHeap);
/* 힙 크기 반환 */
int size = maxHeap.size();
System.out.format("\n힙의 원소 개수: %d\n", size);
/* 힙이 비어 있는지 판단 */
boolean isEmpty = maxHeap.isEmpty();
System.out.format("\n힙이 비어 있는가: %b\n", isEmpty);
/* 리스트를 입력하여 힙 구성 */
// 시간 복잡도는 O(n)이며 O(nlogn)이 아니다
minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
System.out.println("\n리스트를 입력하여 최소 힙을 구성한 후");
PrintUtil.printHeap(minHeap);
}
}

View File

@@ -0,0 +1,159 @@
/**
* File: my_heap.java
* Created Time: 2023-01-07
* Author: krahets (krahets@163.com)
*/
package chapter_heap;
import utils.*;
import java.util.*;
/* 최대 힙 */
class MaxHeap {
// 배열 대신 리스트를 사용하므로 용량 확장을 고려할 필요가 없다
private List<Integer> maxHeap;
/* 생성자: 입력 리스트를 바탕으로 힙 구성 */
public MaxHeap(List<Integer> nums) {
// 리스트 원소를 그대로 힙에 추가한다
maxHeap = new ArrayList<>(nums);
// 리프 노드를 제외한 모든 노드에 힙 재정렬을 수행한다
for (int i = parent(size() - 1); i >= 0; i--) {
siftDown(i);
}
}
/* 왼쪽 자식 노드의 인덱스 반환 */
private int left(int i) {
return 2 * i + 1;
}
/* 오른쪽 자식 노드의 인덱스 반환 */
private int right(int i) {
return 2 * i + 2;
}
/* 부모 노드의 인덱스 반환 */
private int parent(int i) {
return (i - 1) / 2; // 나눗셈의 결과를 내림한다
}
/* 원소 교환 */
private void swap(int i, int j) {
int tmp = maxHeap.get(i);
maxHeap.set(i, maxHeap.get(j));
maxHeap.set(j, tmp);
}
/* 힙 크기 반환 */
public int size() {
return maxHeap.size();
}
/* 힙이 비어 있는지 판단 */
public boolean isEmpty() {
return size() == 0;
}
/* 힙의 루트 원소 접근 */
public int peek() {
return maxHeap.get(0);
}
/* 힙에 원소 삽입 */
public void push(int val) {
// 노드 추가
maxHeap.add(val);
// 아래에서 위로 힙을 재정렬한다
siftUp(size() - 1);
}
/* 노드 i에서 시작하여 아래에서 위로 힙 재정렬 */
private void siftUp(int i) {
while (true) {
// 노드 i의 부모 노드를 구한다
int p = parent(i);
// 루트 노드를 넘어가거나 노드를 수정할 필요가 없으면 힙 재정렬을 마친다
if (p < 0 || maxHeap.get(i) <= maxHeap.get(p))
break;
// 두 노드를 교환한다
swap(i, p);
// 위쪽으로 힙 재정렬을 반복한다
i = p;
}
}
/* 힙에서 원소 꺼내기 */
public int pop() {
// 비어 있는 경우를 처리한다
if (isEmpty())
throw new IndexOutOfBoundsException();
// 루트 노드와 가장 오른쪽 리프 노드를 교환한다(첫 원소와 마지막 원소 교환)
swap(0, size() - 1);
// 노드 삭제
int val = maxHeap.remove(size() - 1);
// 위에서 아래로 힙을 재정렬한다
siftDown(0);
// 힙의 루트 원소를 반환한다
return val;
}
/* 노드 i에서 시작하여 위에서 아래로 힙 재정렬 */
private void siftDown(int i) {
while (true) {
// 노드 i, l, r 중 값이 가장 큰 노드를 찾아 ma로 표시한다
int l = left(i), r = right(i), ma = i;
if (l < size() && maxHeap.get(l) > maxHeap.get(ma))
ma = l;
if (r < size() && maxHeap.get(r) > maxHeap.get(ma))
ma = r;
// 노드 i의 값이 가장 크거나 인덱스 l, r이 범위를 벗어나면 힙을 더 재정렬할 필요가 없으므로 종료한다
if (ma == i)
break;
// 두 노드를 교환한다
swap(i, ma);
// 아래쪽으로 힙 재정렬을 반복한다
i = ma;
}
}
/* 힙 출력(이진 트리) */
public void print() {
Queue<Integer> queue = new PriorityQueue<>((a, b) -> { return b - a; });
queue.addAll(maxHeap);
PrintUtil.printHeap(queue);
}
}
public class my_heap {
public static void main(String[] args) {
/* 최대 힙 초기화 */
MaxHeap maxHeap = new MaxHeap(Arrays.asList(9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2));
System.out.println("\n리스트를 입력하여 힙을 구성한 후");
maxHeap.print();
/* 힙의 루트 원소 반환 */
int peek = maxHeap.peek();
System.out.format("\n힙의 루트 원소: %d\n", peek);
/* 힙에 원소 삽입 */
int val = 7;
maxHeap.push(val);
System.out.format("\n원소를 힙에 삽입한 후(원소: %d)\n", val);
maxHeap.print();
/* 힙의 루트 원소 꺼내기 */
peek = maxHeap.pop();
System.out.format("\n힙의 루트 원소를 꺼낸 후(원소: %d)\n", peek);
maxHeap.print();
/* 힙 크기 반환 */
int size = maxHeap.size();
System.out.format("\n힙의 원소 개수: %d\n", size);
/* 힙이 비어 있는지 판단 */
boolean isEmpty = maxHeap.isEmpty();
System.out.format("\n힙이 비어 있는가: %b\n", isEmpty);
}
}

View File

@@ -0,0 +1,40 @@
/**
* File: top_k.java
* Created Time: 2023-06-12
* Author: krahets (krahets@163.com)
*/
package chapter_heap;
import utils.*;
import java.util.*;
public class top_k {
/* 힙을 이용하여 배열에서 가장 큰 k개 원소 탐색 */
static Queue<Integer> topKHeap(int[] nums, int k) {
// 최소 힙 초기화
Queue<Integer> heap = new PriorityQueue<Integer>();
// 배열의 앞쪽 k개 원소를 힙에 삽입한다
for (int i = 0; i < k; i++) {
heap.offer(nums[i]);
}
// k+1번째 원소부터 힙의 길이를 k로 유지한다
for (int i = k; i < nums.length; i++) {
// 현재 원소가 힙의 루트 원소보다 크면 루트 원소를 꺼내고 현재 원소를 힙에 삽입한다
if (nums[i] > heap.peek()) {
heap.poll();
heap.offer(nums[i]);
}
}
return heap;
}
public static void main(String[] args) {
int[] nums = { 1, 7, 6, 3, 2 };
int k = 3;
Queue<Integer> res = topKHeap(nums, k);
System.out.println("가장 큰 " + k + " 개 원소:");
PrintUtil.printHeap(res);
}
}

View File

@@ -0,0 +1,58 @@
/**
* File: binary_search.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_searching;
public class binary_search {
/* 이진 탐색(양 끝을 포함하는 닫힌 구간) */
static int binarySearch(int[] nums, int target) {
// 닫힌 구간 [0, n-1]을 초기화한다. i와 j는 각각 배열의 첫 원소와 마지막 원소를 가리킨다
int i = 0, j = nums.length - 1;
// 반복하다 탐색 구간이 비면 종료한다(i > j이면 빈 구간이다)
while (i <= j) {
int m = i + (j - i) / 2; // 중간 인덱스 m을 계산한다
if (nums[m] < target) // 이 경우 target은 구간 [m+1, j]에 있다
i = m + 1;
else if (nums[m] > target) // 이 경우 target은 구간 [i, m-1]에 있다
j = m - 1;
else // 목표 원소를 찾았으므로 해당 인덱스를 반환한다
return m;
}
// 목표 원소를 찾지 못했으므로 -1을 반환한다
return -1;
}
/* 이진 탐색(왼쪽 끝은 포함하고 오른쪽 끝은 제외하는 구간) */
static int binarySearchLCRO(int[] nums, int target) {
// 왼쪽 끝만 포함하는 구간 [0, n)을 초기화한다. i는 배열의 첫 원소를, j는 마지막 원소 바로 다음 위치를 가리킨다
int i = 0, j = nums.length;
// 반복하다 탐색 구간이 비면 종료한다(i = j이면 빈 구간이다)
while (i < j) {
int m = i + (j - i) / 2; // 중간 인덱스 m을 계산한다
if (nums[m] < target) // 이 경우 target은 구간 [m+1, j)에 있다
i = m + 1;
else if (nums[m] > target) // 이 경우 target은 구간 [i, m)에 있다
j = m;
else // 목표 원소를 찾았으므로 해당 인덱스를 반환한다
return m;
}
// 목표 원소를 찾지 못했으므로 -1을 반환한다
return -1;
}
public static void main(String[] args) {
int target = 6;
int[] nums = { 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 };
/* 이진 탐색(양 끝을 포함하는 닫힌 구간) */
int index = binarySearch(nums, target);
System.out.println("목표 원소 6의 인덱스 = " + index);
/* 이진 탐색(왼쪽 끝은 포함하고 오른쪽 끝은 제외하는 구간) */
index = binarySearchLCRO(nums, target);
System.out.println("목표 원소 6의 인덱스 = " + index);
}
}

View File

@@ -0,0 +1,49 @@
/**
* File: binary_search_edge.java
* Created Time: 2023-08-04
* Author: krahets (krahets@163.com)
*/
package chapter_searching;
public class binary_search_edge {
/* 가장 왼쪽에 있는 target을 이진 탐색 */
static int binarySearchLeftEdge(int[] nums, int target) {
// target의 삽입 위치를 찾는 것과 같다
int i = binary_search_insertion.binarySearchInsertion(nums, target);
// target을 찾지 못했으므로 -1을 반환한다
if (i == nums.length || nums[i] != target) {
return -1;
}
// target을 찾았으므로 인덱스 i를 반환한다
return i;
}
/* 가장 오른쪽에 있는 target을 이진 탐색 */
static int binarySearchRightEdge(int[] nums, int target) {
// 가장 왼쪽에 있는 target + 1을 찾는 문제로 바꾼다
int i = binary_search_insertion.binarySearchInsertion(nums, target + 1);
// j는 가장 오른쪽의 target을 가리키고, i는 target보다 큰 첫 번째 원소를 가리킨다
int j = i - 1;
// target을 찾지 못했으므로 -1을 반환한다
if (j == -1 || nums[j] != target) {
return -1;
}
// target을 찾았으므로 인덱스 j를 반환한다
return j;
}
public static void main(String[] args) {
// 중복 원소를 포함하는 배열
int[] nums = { 1, 3, 6, 6, 6, 6, 6, 10, 12, 15 };
System.out.println("\n배열 nums = " + java.util.Arrays.toString(nums));
// 왼쪽 경계와 오른쪽 경계의 이진 탐색
for (int target : new int[] { 6, 7 }) {
int index = binarySearchLeftEdge(nums, target);
System.out.println("가장 왼쪽 원소 " + target + " ; 인덱스: " + index);
index = binarySearchRightEdge(nums, target);
System.out.println("가장 오른쪽 원소 " + target + " ; 인덱스: " + index);
}
}
}

View File

@@ -0,0 +1,63 @@
/**
* File: binary_search_insertion.java
* Created Time: 2023-08-04
* Author: krahets (krahets@163.com)
*/
package chapter_searching;
class binary_search_insertion {
/* 삽입 위치의 이진 탐색(중복 원소 없음) */
static int binarySearchInsertionSimple(int[] nums, int target) {
int i = 0, j = nums.length - 1; // 닫힌 구간 [0, n-1]을 초기화한다
while (i <= j) {
int m = i + (j - i) / 2; // 중간 인덱스 m을 계산한다
if (nums[m] < target) {
i = m + 1; // target은 구간 [m+1, j]에 있다
} else if (nums[m] > target) {
j = m - 1; // target은 구간 [i, m-1]에 있다
} else {
return m; // target을 찾았으므로 삽입 위치 m을 반환한다
}
}
// target을 찾지 못했으므로 삽입 위치 i를 반환한다
return i;
}
/* 삽입 위치의 이진 탐색(중복 원소 있음) */
static int binarySearchInsertion(int[] nums, int target) {
int i = 0, j = nums.length - 1; // 닫힌 구간 [0, n-1]을 초기화한다
while (i <= j) {
int m = i + (j - i) / 2; // 중간 인덱스 m을 계산한다
if (nums[m] < target) {
i = m + 1; // target은 구간 [m+1, j]에 있다
} else if (nums[m] > target) {
j = m - 1; // target은 구간 [i, m-1]에 있다
} else {
j = m - 1; // target보다 작은 가장 오른쪽 원소는 구간 [i, m-1]에 있다
}
}
// 삽입 위치 i를 반환한다
return i;
}
public static void main(String[] args) {
// 중복 원소가 없는 배열
int[] nums = { 1, 3, 6, 8, 12, 15, 23, 26, 31, 35 };
System.out.println("\n배열 nums = " + java.util.Arrays.toString(nums));
// 삽입 위치의 이진 탐색
for (int target : new int[] { 6, 9 }) {
int index = binarySearchInsertionSimple(nums, target);
System.out.println("원소 " + target + " ; 삽입 위치의 인덱스: " + index);
}
// 중복 원소를 포함하는 배열
nums = new int[] { 1, 3, 6, 6, 6, 6, 6, 10, 12, 15 };
System.out.println("\n배열 nums = " + java.util.Arrays.toString(nums));
// 삽입 위치의 이진 탐색
for (int target : new int[] { 2, 6, 20 }) {
int index = binarySearchInsertion(nums, target);
System.out.println("원소 " + target + " ; 삽입 위치의 인덱스: " + index);
}
}
}

View File

@@ -0,0 +1,51 @@
/**
* File: hashing_search.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_searching;
import utils.*;
import java.util.*;
public class hashing_search {
/* 해시 탐색(배열) */
static int hashingSearchArray(Map<Integer, Integer> map, int target) {
// 해시 테이블의 key: 목표 원소, value: 인덱스
// 해시 테이블에 해당 key가 없으면 -1을 반환한다
return map.getOrDefault(target, -1);
}
/* 해시 탐색(연결 리스트) */
static ListNode hashingSearchLinkedList(Map<Integer, ListNode> map, int target) {
// 해시 테이블의 key: 목표 노드의 값, value: 노드 객체
// 해시 테이블에 해당 key가 없으면 null을 반환한다
return map.getOrDefault(target, null);
}
public static void main(String[] args) {
int target = 3;
/* 해시 탐색(배열) */
int[] nums = { 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 };
// 해시 테이블 초기화
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i); // key: 원소, value: 인덱스
}
int index = hashingSearchArray(map, target);
System.out.println("목표 원소 3의 인덱스 = " + index);
/* 해시 탐색(연결 리스트) */
ListNode head = ListNode.arrToLinkedList(nums);
// 해시 테이블 초기화
Map<Integer, ListNode> map1 = new HashMap<>();
while (head != null) {
map1.put(head.val, head); // key: 노드 값, value: 노드
head = head.next;
}
ListNode node = hashingSearchLinkedList(map1, target);
System.out.println("목표 노드 값 3에 해당하는 노드 객체 " + node);
}
}

View File

@@ -0,0 +1,50 @@
/**
* File: linear_search.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_searching;
import utils.*;
public class linear_search {
/* 선형 탐색(배열) */
static int linearSearchArray(int[] nums, int target) {
// 배열 순회
for (int i = 0; i < nums.length; i++) {
// 목표 원소를 찾았으므로 해당 인덱스를 반환한다
if (nums[i] == target)
return i;
}
// 목표 원소를 찾지 못했으므로 -1을 반환한다
return -1;
}
/* 선형 탐색(연결 리스트) */
static ListNode linearSearchLinkedList(ListNode head, int target) {
// 연결 리스트 순회
while (head != null) {
// 목표 노드를 찾았으므로 해당 노드를 반환한다
if (head.val == target)
return head;
head = head.next;
}
// 목표 노드를 찾지 못했으므로 null을 반환한다
return null;
}
public static void main(String[] args) {
int target = 3;
/* 배열에서 선형 탐색을 수행한다 */
int[] nums = { 1, 5, 3, 2, 4, 7, 5, 9, 10, 8 };
int index = linearSearchArray(nums, target);
System.out.println("목표 원소 3의 인덱스 = " + index);
/* 연결 리스트에서 선형 탐색을 수행한다 */
ListNode head = ListNode.arrToLinkedList(nums);
ListNode node = linearSearchLinkedList(head, target);
System.out.println("목표 노드 값 3에 해당하는 노드 객체 " + node);
}
}

View File

@@ -0,0 +1,53 @@
/**
* File: two_sum.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_searching;
import java.util.*;
public class two_sum {
/* 방법 1: 완전 열거 */
static int[] twoSumBruteForce(int[] nums, int target) {
int size = nums.length;
// 이중 반복문이며 시간 복잡도는 O(n^2)이다
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (nums[i] + nums[j] == target)
return new int[] { i, j };
}
}
return new int[0];
}
/* 방법 2: 보조 해시 테이블 */
static int[] twoSumHashTable(int[] nums, int target) {
int size = nums.length;
// 보조 해시 테이블의 공간 복잡도는 O(n)이다
Map<Integer, Integer> dic = new HashMap<>();
// 단일 반복문이며 시간 복잡도는 O(n)이다
for (int i = 0; i < size; i++) {
if (dic.containsKey(target - nums[i])) {
return new int[] { dic.get(target - nums[i]), i };
}
dic.put(nums[i], i);
}
return new int[0];
}
public static void main(String[] args) {
// ======= 테스트 사례 =======
int[] nums = { 2, 7, 11, 15 };
int target = 13;
// ====== 실행 코드 ======
// 방법 1
int[] res = twoSumBruteForce(nums, target);
System.out.println("방법 1 res = " + Arrays.toString(res));
// 방법 2
res = twoSumHashTable(nums, target);
System.out.println("방법 2 res = " + Arrays.toString(res));
}
}

View File

@@ -0,0 +1,57 @@
/**
* File: bubble_sort.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;
public class bubble_sort {
/* 버블 정렬 */
static void bubbleSort(int[] nums) {
// 바깥쪽 반복문: 정렬되지 않은 구간은 [0, i]이다
for (int i = nums.length - 1; i > 0; i--) {
// 안쪽 반복문: 정렬되지 않은 구간 [0, i]의 최댓값을 교환하여 이 구간의 맨 오른쪽으로 옮긴다
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// nums[j]와 nums[j + 1]을 교환한다
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
}
}
}
}
/* 버블 정렬(플래그 최적화) */
static void bubbleSortWithFlag(int[] nums) {
// 바깥쪽 반복문: 정렬되지 않은 구간은 [0, i]이다
for (int i = nums.length - 1; i > 0; i--) {
boolean flag = false; // 플래그를 초기화한다
// 안쪽 반복문: 정렬되지 않은 구간 [0, i]의 최댓값을 교환하여 이 구간의 맨 오른쪽으로 옮긴다
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// nums[j]와 nums[j + 1]을 교환한다
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
flag = true; // 원소가 교환되었음을 기록한다
}
}
if (!flag)
break; // 이번 버블 과정에서 원소 교환이 없었으므로 바로 종료한다
}
}
public static void main(String[] args) {
int[] nums = { 4, 1, 3, 1, 5, 2 };
bubbleSort(nums);
System.out.println("버블 정렬을 마친 후 nums = " + Arrays.toString(nums));
int[] nums1 = { 4, 1, 3, 1, 5, 2 };
bubbleSortWithFlag(nums1);
System.out.println("버블 정렬을 마친 후 nums1 = " + Arrays.toString(nums1));
}
}

View File

@@ -0,0 +1,47 @@
/**
* File: bucket_sort.java
* Created Time: 2023-03-17
* Author: krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;
public class bucket_sort {
/* 버킷 정렬 */
static void bucketSort(float[] nums) {
// 버킷 k = n/2개를 초기화하며, 각 버킷에 원소 2개가 배정될 것으로 예상한다
int k = nums.length / 2;
List<List<Float>> buckets = new ArrayList<>();
for (int i = 0; i < k; i++) {
buckets.add(new ArrayList<>());
}
// 1. 배열 원소를 각 버킷에 배정한다
for (float num : nums) {
// 입력 데이터의 범위는 [0, 1)이며, num * k를 사용하여 인덱스 범위 [0, k-1]에 대응시킨다
int i = (int) (num * k);
// num을 버킷 i에 추가한다
buckets.get(i).add(num);
}
// 2. 각 버킷을 정렬한다
for (List<Float> bucket : buckets) {
// 내장 정렬 함수를 사용하며, 다른 정렬 알고리즘으로 대체할 수도 있다
Collections.sort(bucket);
}
// 3. 버킷을 순회하여 결과를 합친다
int i = 0;
for (List<Float> bucket : buckets) {
for (float num : bucket) {
nums[i++] = num;
}
}
}
public static void main(String[] args) {
// 입력 데이터는 범위가 [0, 1)인 부동 소수점 수라고 가정한다
float[] nums = { 0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f };
bucketSort(nums);
System.out.println("버킷 정렬을 마친 후 nums = " + Arrays.toString(nums));
}
}

View File

@@ -0,0 +1,78 @@
/**
* File: counting_sort.java
* Created Time: 2023-03-17
* Author: krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;
public class counting_sort {
/* 계수 정렬 */
// 간단한 구현이며, 객체 정렬에는 사용할 수 없다
static void countingSortNaive(int[] nums) {
// 1. 배열의 최댓값 m을 구한다
int m = 0;
for (int num : nums) {
m = Math.max(m, num);
}
// 2. 각 숫자의 등장 횟수를 센다
// counter[num]은 num의 등장 횟수를 나타낸다
int[] counter = new int[m + 1];
for (int num : nums) {
counter[num]++;
}
// 3. counter를 순회하며 각 원소를 원래 배열 nums에 채운다
int i = 0;
for (int num = 0; num < m + 1; num++) {
for (int j = 0; j < counter[num]; j++, i++) {
nums[i] = num;
}
}
}
/* 계수 정렬 */
// 완전한 구현이며, 객체를 정렬할 수 있고 안정 정렬이다
static void countingSort(int[] nums) {
// 1. 배열의 최댓값 m을 구한다
int m = 0;
for (int num : nums) {
m = Math.max(m, num);
}
// 2. 각 숫자의 등장 횟수를 센다
// counter[num]은 num의 등장 횟수를 나타낸다
int[] counter = new int[m + 1];
for (int num : nums) {
counter[num]++;
}
// 3. counter의 접두 합을 구하여 등장 횟수를 마지막 인덱스로 변환한다
// 즉, counter[num]-1은 res에서 num이 마지막으로 등장하는 인덱스이다
for (int i = 0; i < m; i++) {
counter[i + 1] += counter[i];
}
// 4. nums를 역순으로 순회하며 각 원소를 결과 배열 res에 채운다
// 결과를 기록할 배열 res를 초기화한다
int n = nums.length;
int[] res = new int[n];
for (int i = n - 1; i >= 0; i--) {
int num = nums[i];
res[counter[num] - 1] = num; // num을 해당 인덱스에 배치한다
counter[num]--; // 접두 합을 1 감소시켜 다음에 num을 배치할 인덱스를 구한다
}
// 결과 배열 res로 원래 배열 nums를 덮어쓴다
for (int i = 0; i < n; i++) {
nums[i] = res[i];
}
}
public static void main(String[] args) {
int[] nums = { 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 };
countingSortNaive(nums);
System.out.println("계수 정렬(객체 정렬 불가)을 마친 후 nums = " + Arrays.toString(nums));
int[] nums1 = { 1, 0, 1, 2, 0, 4, 0, 2, 2, 4 };
countingSort(nums1);
System.out.println("계수 정렬을 마친 후 nums1 = " + Arrays.toString(nums1));
}
}

View File

@@ -0,0 +1,57 @@
/**
* File: heap_sort.java
* Created Time: 2023-05-26
* Author: krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.Arrays;
public class heap_sort {
/* 길이가 n인 힙에서 노드 i부터 위에서 아래로 힙 재정렬 */
public static void siftDown(int[] nums, int n, int i) {
while (true) {
// 노드 i, l, r 중 값이 가장 큰 노드를 찾아 ma로 표시한다
int l = 2 * i + 1;
int r = 2 * i + 2;
int ma = i;
if (l < n && nums[l] > nums[ma])
ma = l;
if (r < n && nums[r] > nums[ma])
ma = r;
// 노드 i의 값이 가장 크거나 인덱스 l, r이 범위를 벗어나면 힙을 더 재정렬할 필요가 없으므로 종료한다
if (ma == i)
break;
// 두 노드를 교환한다
int temp = nums[i];
nums[i] = nums[ma];
nums[ma] = temp;
// 아래쪽으로 힙 재정렬을 반복한다
i = ma;
}
}
/* 힙 정렬 */
public static void heapSort(int[] nums) {
// 힙 구성 연산: 리프 노드를 제외한 모든 노드에 힙 재정렬을 수행한다
for (int i = nums.length / 2 - 1; i >= 0; i--) {
siftDown(nums, nums.length, i);
}
// 힙에서 최댓값을 꺼내는 작업을 n-1회 반복한다
for (int i = nums.length - 1; i > 0; i--) {
// 루트 노드와 가장 오른쪽 리프 노드를 교환한다(첫 원소와 마지막 원소 교환)
int tmp = nums[0];
nums[0] = nums[i];
nums[i] = tmp;
// 루트 노드에서 시작하여 위에서 아래로 힙을 재정렬한다
siftDown(nums, i, 0);
}
}
public static void main(String[] args) {
int[] nums = { 4, 1, 3, 1, 5, 2 };
heapSort(nums);
System.out.println("힙 정렬을 마친 후 nums = " + Arrays.toString(nums));
}
}

View File

@@ -0,0 +1,31 @@
/**
* File: insertion_sort.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;
public class insertion_sort {
/* 삽입 정렬 */
static void insertionSort(int[] nums) {
// 바깥쪽 반복문: 정렬된 구간은 [0, i-1]이다
for (int i = 1; i < nums.length; i++) {
int base = nums[i], j = i - 1;
// 안쪽 반복문: base를 정렬된 구간 [0, i-1]의 올바른 위치에 삽입한다
while (j >= 0 && nums[j] > base) {
nums[j + 1] = nums[j]; // nums[j]를 오른쪽으로 한 칸 이동한다
j--;
}
nums[j + 1] = base; // 올바른 위치에 base를 대입한다
}
}
public static void main(String[] args) {
int[] nums = { 4, 1, 3, 1, 5, 2 };
insertionSort(nums);
System.out.println("삽입 정렬을 마친 후 nums = " + Arrays.toString(nums));
}
}

View File

@@ -0,0 +1,58 @@
/**
* File: merge_sort.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;
public class merge_sort {
/* 왼쪽 부분 배열과 오른쪽 부분 배열 병합 */
static void merge(int[] nums, int left, int mid, int right) {
// 왼쪽 부분 배열의 구간은 [left, mid]이고, 오른쪽 부분 배열의 구간은 [mid+1, right]이다
// 병합 결과를 저장할 임시 배열 tmp를 생성한다
int[] tmp = new int[right - left + 1];
// 왼쪽 부분 배열과 오른쪽 부분 배열의 시작 인덱스를 초기화한다
int i = left, j = mid + 1, k = 0;
// 양쪽 부분 배열 모두에 원소가 남아 있으면 비교하여 더 작은 원소를 임시 배열에 복사한다
while (i <= mid && j <= right) {
if (nums[i] <= nums[j])
tmp[k++] = nums[i++];
else
tmp[k++] = nums[j++];
}
// 왼쪽 부분 배열과 오른쪽 부분 배열의 남은 원소를 임시 배열에 복사한다
while (i <= mid) {
tmp[k++] = nums[i++];
}
while (j <= right) {
tmp[k++] = nums[j++];
}
// 임시 배열 tmp의 원소를 원래 배열 nums의 해당 구간에 다시 복사한다
for (k = 0; k < tmp.length; k++) {
nums[left + k] = tmp[k];
}
}
/* 병합 정렬 */
static void mergeSort(int[] nums, int left, int right) {
// 종료 조건
if (left >= right)
return; // 부분 배열의 길이가 1이면 재귀를 종료한다
// 분할 단계
int mid = left + (right - left) / 2; // 중간 위치를 계산한다
mergeSort(nums, left, mid); // 왼쪽 부분 배열에 재귀 호출한다
mergeSort(nums, mid + 1, right); // 오른쪽 부분 배열에 재귀 호출한다
// 병합 단계
merge(nums, left, mid, right);
}
public static void main(String[] args) {
/* 병합 정렬 */
int[] nums = { 7, 3, 2, 6, 0, 1, 5, 4 };
mergeSort(nums, 0, nums.length - 1);
System.out.println("병합 정렬을 마친 후 nums = " + Arrays.toString(nums));
}
}

View File

@@ -0,0 +1,158 @@
/**
* File: quick_sort.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;
/* 퀵 정렬 클래스 */
class QuickSort {
/* 원소 교환 */
static void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* 센티널 분할 */
static int partition(int[] nums, int left, int right) {
// nums[left]를 피벗으로 삼는다
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--; // 오른쪽에서 왼쪽으로 피벗보다 작은 첫 번째 원소를 찾는다
while (i < j && nums[i] <= nums[left])
i++; // 왼쪽에서 오른쪽으로 피벗보다 큰 첫 번째 원소를 찾는다
swap(nums, i, j); // 두 원소를 교환한다
}
swap(nums, i, left); // 피벗을 두 부분 배열의 경계로 교환하여 옮긴다
return i; // 피벗의 인덱스를 반환한다
}
/* 퀵 정렬 */
public static void quickSort(int[] nums, int left, int right) {
// 부분 배열의 길이가 1이면 재귀를 종료한다
if (left >= right)
return;
// 센티널 분할
int pivot = partition(nums, left, right);
// 왼쪽 부분 배열과 오른쪽 부분 배열에 재귀 호출한다
quickSort(nums, left, pivot - 1);
quickSort(nums, pivot + 1, right);
}
}
/* 퀵 정렬 클래스(중앙값 피벗 최적화) */
class QuickSortMedian {
/* 원소 교환 */
static void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* 세 후보 원소의 중앙값 선택 */
static int medianThree(int[] nums, int left, int mid, int right) {
int l = nums[left], m = nums[mid], r = nums[right];
if ((l <= m && m <= r) || (r <= m && m <= l))
return mid; // m은 l과 r 사이에 있다
if ((m <= l && l <= r) || (r <= l && l <= m))
return left; // l은 m과 r 사이에 있다
return right;
}
/* 센티널 분할(세 수의 중앙값 선택) */
static int partition(int[] nums, int left, int right) {
// 세 후보 원소의 중앙값 선택
int med = medianThree(nums, left, (left + right) / 2, right);
// 중앙값을 배열 맨 왼쪽으로 교환하여 옮긴다
swap(nums, left, med);
// nums[left]를 피벗으로 삼는다
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--; // 오른쪽에서 왼쪽으로 피벗보다 작은 첫 번째 원소를 찾는다
while (i < j && nums[i] <= nums[left])
i++; // 왼쪽에서 오른쪽으로 피벗보다 큰 첫 번째 원소를 찾는다
swap(nums, i, j); // 두 원소를 교환한다
}
swap(nums, i, left); // 피벗을 두 부분 배열의 경계로 교환하여 옮긴다
return i; // 피벗의 인덱스를 반환한다
}
/* 퀵 정렬 */
public static void quickSort(int[] nums, int left, int right) {
// 부분 배열의 길이가 1이면 재귀를 종료한다
if (left >= right)
return;
// 센티널 분할
int pivot = partition(nums, left, right);
// 왼쪽 부분 배열과 오른쪽 부분 배열에 재귀 호출한다
quickSort(nums, left, pivot - 1);
quickSort(nums, pivot + 1, right);
}
}
/* 퀵 정렬 클래스(재귀 깊이 최적화) */
class QuickSortTailCall {
/* 원소 교환 */
static void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* 센티널 분할 */
static int partition(int[] nums, int left, int right) {
// nums[left]를 피벗으로 삼는다
int i = left, j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left])
j--; // 오른쪽에서 왼쪽으로 피벗보다 작은 첫 번째 원소를 찾는다
while (i < j && nums[i] <= nums[left])
i++; // 왼쪽에서 오른쪽으로 피벗보다 큰 첫 번째 원소를 찾는다
swap(nums, i, j); // 두 원소를 교환한다
}
swap(nums, i, left); // 피벗을 두 부분 배열의 경계로 교환하여 옮긴다
return i; // 피벗의 인덱스를 반환한다
}
/* 퀵 정렬(재귀 깊이 최적화) */
public static void quickSort(int[] nums, int left, int right) {
// 부분 배열의 길이가 1이면 종료한다
while (left < right) {
// 센티널 분할 연산
int pivot = partition(nums, left, right);
// 두 부분 배열 중 더 짧은 쪽에 퀵 정렬을 수행한다
if (pivot - left < right - pivot) {
quickSort(nums, left, pivot - 1); // 왼쪽 부분 배열을 재귀적으로 정렬한다
left = pivot + 1; // 남은 미정렬 구간은 [pivot + 1, right]이다
} else {
quickSort(nums, pivot + 1, right); // 오른쪽 부분 배열을 재귀적으로 정렬한다
right = pivot - 1; // 남은 미정렬 구간은 [left, pivot - 1]이다
}
}
}
}
public class quick_sort {
public static void main(String[] args) {
/* 퀵 정렬 */
int[] nums = { 2, 4, 1, 0, 3, 5 };
QuickSort.quickSort(nums, 0, nums.length - 1);
System.out.println("퀵 정렬을 마친 후 nums = " + Arrays.toString(nums));
/* 퀵 정렬(중앙값 피벗 최적화) */
int[] nums1 = { 2, 4, 1, 0, 3, 5 };
QuickSortMedian.quickSort(nums1, 0, nums1.length - 1);
System.out.println("퀵 정렬(중앙값 피벗 최적화)을 마친 후 nums1 = " + Arrays.toString(nums1));
/* 퀵 정렬(재귀 깊이 최적화) */
int[] nums2 = { 2, 4, 1, 0, 3, 5 };
QuickSortTailCall.quickSort(nums2, 0, nums2.length - 1);
System.out.println("퀵 정렬(재귀 깊이 최적화)을 마친 후 nums2 = " + Arrays.toString(nums2));
}
}

View File

@@ -0,0 +1,69 @@
/**
* File: radix_sort.java
* Created Time: 2023-01-17
* Author: krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.*;
public class radix_sort {
/* 원소 num의 k번째 자릿값 반환. 이때 exp = 10^(k-1)이다 */
static int digit(int num, int exp) {
// k 대신 exp를 전달하면 여기서 비용이 큰 거듭제곱 계산을 반복하지 않아도 된다
return (num / exp) % 10;
}
/* 계수 정렬(nums의 k번째 자릿값을 기준으로 정렬) */
static void countingSortDigit(int[] nums, int exp) {
// 십진수의 각 자리는 0~9 범위이므로 길이가 10인 버킷 배열이 필요하다
int[] counter = new int[10];
int n = nums.length;
// 0~9 각 숫자의 등장 횟수를 센다
for (int i = 0; i < n; i++) {
int d = digit(nums[i], exp); // nums[i]의 k번째 자릿값을 구하여 d로 표시한다
counter[d]++; // 숫자 d의 등장 횟수를 센다
}
// 접두 합을 구하여 등장 개수를 배열 인덱스로 변환한다
for (int i = 1; i < 10; i++) {
counter[i] += counter[i - 1];
}
// 역순으로 순회하며 버킷에 집계된 결과에 따라 각 원소를 res에 채운다
int[] res = new int[n];
for (int i = n - 1; i >= 0; i--) {
int d = digit(nums[i], exp);
int j = counter[d] - 1; // 배열에서 d의 인덱스 j를 구한다
res[j] = nums[i]; // 현재 원소를 인덱스 j에 채운다
counter[d]--; // d의 개수를 1 줄인다
}
// 결과로 원래 배열 nums를 덮어쓴다
for (int i = 0; i < n; i++)
nums[i] = res[i];
}
/* 기수 정렬 */
static void radixSort(int[] nums) {
// 배열의 최댓값을 구하여 최대 자릿수를 판단한다
int m = Integer.MIN_VALUE;
for (int num : nums)
if (num > m)
m = num;
// 낮은 자리에서 높은 자리 순서로 순회한다
for (int exp = 1; exp <= m; exp *= 10) {
// 배열 원소의 k번째 자릿값에 대해 계수 정렬을 수행한다
// k = 1 -> exp = 1
// k = 2 -> exp = 10
// 즉, exp = 10^(k-1)이다
countingSortDigit(nums, exp);
}
}
public static void main(String[] args) {
// 기수 정렬
int[] nums = { 10546151, 35663510, 42865989, 34862445, 81883077,
88906420, 72429244, 30524779, 82060337, 63832996 };
radixSort(nums);
System.out.println("기수 정렬을 마친 후 nums = " + Arrays.toString(nums));
}
}

View File

@@ -0,0 +1,35 @@
/**
* File: selection_sort.java
* Created Time: 2023-05-23
* Author: krahets (krahets@163.com)
*/
package chapter_sorting;
import java.util.Arrays;
public class selection_sort {
/* 선택 정렬 */
public static void selectionSort(int[] nums) {
int n = nums.length;
// 바깥쪽 반복문: 정렬되지 않은 구간은 [i, n-1]이다
for (int i = 0; i < n - 1; i++) {
// 안쪽 반복문: 정렬되지 않은 구간의 최솟값을 찾는다
int k = i;
for (int j = i + 1; j < n; j++) {
if (nums[j] < nums[k])
k = j; // 최솟값의 인덱스를 기록한다
}
// 이 최솟값과 정렬되지 않은 구간의 첫 원소를 교환한다
int temp = nums[i];
nums[i] = nums[k];
nums[k] = temp;
}
}
public static void main(String[] args) {
int[] nums = { 4, 1, 3, 1, 5, 2 };
selectionSort(nums);
System.out.println("선택 정렬을 마친 후 nums = " + Arrays.toString(nums));
}
}

View File

@@ -0,0 +1,151 @@
/**
* File: array_deque.java
* Created Time: 2023-02-16
* Author: krahets (krahets@163.com), FangYuan33 (374072213@qq.com)
*/
package chapter_stack_and_queue;
import java.util.*;
/* 원형 배열로 구현한 덱 */
class ArrayDeque {
private int[] nums; // 덱의 원소를 저장하는 배열
private int front; // 맨 앞 원소를 가리키는 맨 앞 포인터
private int queSize; // 덱 길이
/* 생성자 */
public ArrayDeque(int capacity) {
this.nums = new int[capacity];
front = queSize = 0;
}
/* 덱의 용량 반환 */
public int capacity() {
return nums.length;
}
/* 덱의 길이 반환 */
public int size() {
return queSize;
}
/* 덱이 비어 있는지 판단 */
public boolean isEmpty() {
return queSize == 0;
}
/* 원형 배열 인덱스 계산 */
private int index(int i) {
// 나머지 연산을 통해 배열의 처음과 끝을 연결한다
// i가 배열의 끝을 넘어가면 처음으로 돌아온다
// i가 배열의 처음을 넘어가면 끝으로 돌아온다
return (i + capacity()) % capacity();
}
/* 맨 앞에 삽입 */
public void pushFirst(int num) {
if (queSize == capacity()) {
System.out.println("덱이 가득 찼다");
return;
}
// 맨 앞 포인터를 왼쪽으로 한 칸 이동한다
// 나머지 연산을 통해 front가 배열의 처음을 넘어가면 끝으로 돌아오게 한다
front = index(front - 1);
// num을 맨 앞에 추가한다
nums[front] = num;
queSize++;
}
/* 맨 뒤에 삽입 */
public void pushLast(int num) {
if (queSize == capacity()) {
System.out.println("덱이 가득 찼다");
return;
}
// 맨 뒤 인덱스 + 1을 가리키는 맨 뒤 포인터를 계산한다
int rear = index(front + queSize);
// num을 맨 뒤에 추가한다
nums[rear] = num;
queSize++;
}
/* 맨 앞에서 꺼내기 */
public int popFirst() {
int num = peekFirst();
// 맨 앞 포인터를 뒤로 한 칸 이동한다
front = index(front + 1);
queSize--;
return num;
}
/* 맨 뒤에서 꺼내기 */
public int popLast() {
int num = peekLast();
queSize--;
return num;
}
/* 맨 앞 원소 접근 */
public int peekFirst() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return nums[front];
}
/* 맨 뒤 원소 접근 */
public int peekLast() {
if (isEmpty())
throw new IndexOutOfBoundsException();
// 마지막 원소의 인덱스를 계산한다
int last = index(front + queSize - 1);
return nums[last];
}
/* 출력에 사용할 배열 반환 */
public int[] toArray() {
// 유효한 길이 범위 안의 리스트 원소만 변환한다
int[] res = new int[queSize];
for (int i = 0, j = front; i < queSize; i++, j++) {
res[i] = nums[index(j)];
}
return res;
}
}
public class array_deque {
public static void main(String[] args) {
/* 덱 초기화 */
ArrayDeque deque = new ArrayDeque(10);
deque.pushLast(3);
deque.pushLast(2);
deque.pushLast(5);
System.out.println("덱 deque = " + Arrays.toString(deque.toArray()));
/* 원소 접근 */
int peekFirst = deque.peekFirst();
System.out.println("맨 앞 원소 peekFirst = " + peekFirst);
int peekLast = deque.peekLast();
System.out.println("맨 뒤 원소 peekLast = " + peekLast);
/* 큐에 원소 삽입 */
deque.pushLast(4);
System.out.println("원소 4를 맨 뒤에 삽입한 후 deque = " + Arrays.toString(deque.toArray()));
deque.pushFirst(1);
System.out.println("원소 1을 맨 앞에 삽입한 후 deque = " + Arrays.toString(deque.toArray()));
/* 큐에서 원소 꺼내기 */
int popLast = deque.popLast();
System.out.println("맨 뒤에서 꺼낸 원소 = " + popLast + ", 맨 뒤에서 꺼낸 후 deque = " + Arrays.toString(deque.toArray()));
int popFirst = deque.popFirst();
System.out.println("맨 앞에서 꺼낸 원소 = " + popFirst + ", 맨 앞에서 꺼낸 후 deque = " + Arrays.toString(deque.toArray()));
/* 덱의 길이 반환 */
int size = deque.size();
System.out.println("덱 길이 size = " + size);
/* 덱이 비어 있는지 판단 */
boolean isEmpty = deque.isEmpty();
System.out.println("덱이 비어 있는가 = " + isEmpty);
}
}

View File

@@ -0,0 +1,115 @@
/**
* File: array_queue.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_stack_and_queue;
import java.util.*;
/* 원형 배열로 구현한 큐 */
class ArrayQueue {
private int[] nums; // 큐의 원소를 저장하는 배열
private int front; // 맨 앞 원소를 가리키는 맨 앞 포인터
private int queSize; // 큐 길이
public ArrayQueue(int capacity) {
nums = new int[capacity];
front = queSize = 0;
}
/* 큐의 용량 반환 */
public int capacity() {
return nums.length;
}
/* 큐의 길이 반환 */
public int size() {
return queSize;
}
/* 큐가 비어 있는지 판단 */
public boolean isEmpty() {
return queSize == 0;
}
/* 큐에 삽입 */
public void push(int num) {
if (queSize == capacity()) {
System.out.println("큐가 가득 찼다");
return;
}
// 맨 뒤 인덱스 + 1을 가리키는 맨 뒤 포인터를 계산한다
// 나머지 연산을 통해 rear가 배열의 끝을 넘어가면 처음으로 돌아오게 한다
int rear = (front + queSize) % capacity();
// num을 맨 뒤에 추가한다
nums[rear] = num;
queSize++;
}
/* 큐에서 꺼내기 */
public int pop() {
int num = peek();
// 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다
front = (front + 1) % capacity();
queSize--;
return num;
}
/* 맨 앞 원소 접근 */
public int peek() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return nums[front];
}
/* 배열 반환 */
public int[] toArray() {
// 유효한 길이 범위 안의 리스트 원소만 변환한다
int[] res = new int[queSize];
for (int i = 0, j = front; i < queSize; i++, j++) {
res[i] = nums[j % capacity()];
}
return res;
}
}
public class array_queue {
public static void main(String[] args) {
/* 큐 초기화 */
int capacity = 10;
ArrayQueue queue = new ArrayQueue(capacity);
/* 큐에 원소 삽입 */
queue.push(1);
queue.push(3);
queue.push(2);
queue.push(5);
queue.push(4);
System.out.println("큐 queue = " + Arrays.toString(queue.toArray()));
/* 맨 앞 원소 접근 */
int peek = queue.peek();
System.out.println("맨 앞 원소 peek = " + peek);
/* 큐에서 원소 꺼내기 */
int pop = queue.pop();
System.out.println("큐에서 꺼낸 원소 pop = " + pop + ", 큐에서 꺼낸 후 queue = " + Arrays.toString(queue.toArray()));
/* 큐의 길이 반환 */
int size = queue.size();
System.out.println("큐 길이 size = " + size);
/* 큐가 비어 있는지 판단 */
boolean isEmpty = queue.isEmpty();
System.out.println("큐가 비어 있는가 = " + isEmpty);
/* 원형 배열 테스트 */
for (int i = 0; i < 10; i++) {
queue.push(i);
queue.pop();
System.out.println("반복 " + i + " 회에서 삽입 + 꺼내기를 수행한 후 queue = " + Arrays.toString(queue.toArray()));
}
}
}

View File

@@ -0,0 +1,84 @@
/**
* File: array_stack.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_stack_and_queue;
import java.util.*;
/* 배열로 구현한 스택 */
class ArrayStack {
private ArrayList<Integer> stack;
public ArrayStack() {
// 리스트(동적 배열)를 초기화한다
stack = new ArrayList<>();
}
/* 스택의 길이 반환 */
public int size() {
return stack.size();
}
/* 스택이 비어 있는지 판단 */
public boolean isEmpty() {
return size() == 0;
}
/* 스택에 삽입 */
public void push(int num) {
stack.add(num);
}
/* 스택에서 꺼내기 */
public int pop() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return stack.remove(size() - 1);
}
/* 스택 맨 위 원소 접근 */
public int peek() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return stack.get(size() - 1);
}
/* List를 Array로 변환하여 반환 */
public Object[] toArray() {
return stack.toArray();
}
}
public class array_stack {
public static void main(String[] args) {
/* 스택 초기화 */
ArrayStack stack = new ArrayStack();
/* 스택에 원소 삽입 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
System.out.println("스택 stack = " + Arrays.toString(stack.toArray()));
/* 스택 맨 위 원소 접근 */
int peek = stack.peek();
System.out.println("스택 맨 위 원소 peek = " + peek);
/* 스택에서 원소 꺼내기 */
int pop = stack.pop();
System.out.println("스택에서 꺼낸 원소 pop = " + pop + ", 스택에서 꺼낸 후 stack = " + Arrays.toString(stack.toArray()));
/* 스택의 길이 반환 */
int size = stack.size();
System.out.println("스택의 길이 size = " + size);
/* 비어 있는지 판단 */
boolean isEmpty = stack.isEmpty();
System.out.println("스택이 비어 있는가 = " + isEmpty);
}
}

View File

@@ -0,0 +1,46 @@
/**
* File: deque.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_stack_and_queue;
import java.util.*;
public class deque {
public static void main(String[] args) {
/* 덱 초기화 */
Deque<Integer> deque = new LinkedList<>();
deque.offerLast(3);
deque.offerLast(2);
deque.offerLast(5);
System.out.println("덱 deque = " + deque);
/* 원소 접근 */
int peekFirst = deque.peekFirst();
System.out.println("맨 앞 원소 peekFirst = " + peekFirst);
int peekLast = deque.peekLast();
System.out.println("맨 뒤 원소 peekLast = " + peekLast);
/* 큐에 원소 삽입 */
deque.offerLast(4);
System.out.println("원소 4를 맨 뒤에 삽입한 후 deque = " + deque);
deque.offerFirst(1);
System.out.println("원소 1을 맨 앞에 삽입한 후 deque = " + deque);
/* 큐에서 원소 꺼내기 */
int popLast = deque.pollLast();
System.out.println("맨 뒤에서 꺼낸 원소 = " + popLast + ", 맨 뒤에서 꺼낸 후 deque = " + deque);
int popFirst = deque.pollFirst();
System.out.println("맨 앞에서 꺼낸 원소 = " + popFirst + ", 맨 앞에서 꺼낸 후 deque = " + deque);
/* 덱의 길이 반환 */
int size = deque.size();
System.out.println("덱 길이 size = " + size);
/* 덱이 비어 있는지 판단 */
boolean isEmpty = deque.isEmpty();
System.out.println("덱이 비어 있는가 = " + isEmpty);
}
}

View File

@@ -0,0 +1,177 @@
/**
* File: linkedlist_deque.java
* Created Time: 2023-01-20
* Author: krahets (krahets@163.com)
*/
package chapter_stack_and_queue;
import java.util.*;
/* 이중 연결 리스트 노드 */
class ListNode {
int val; // 노드 값
ListNode next; // 다음 노드 참조
ListNode prev; // 이전 노드 참조
ListNode(int val) {
this.val = val;
prev = next = null;
}
}
/* 이중 연결 리스트로 구현한 덱 */
class LinkedListDeque {
private ListNode front, rear; // 머리 노드 front, 꼬리 노드 rear
private int queSize = 0; // 덱의 길이
public LinkedListDeque() {
front = rear = null;
}
/* 덱의 길이 반환 */
public int size() {
return queSize;
}
/* 덱이 비어 있는지 판단 */
public boolean isEmpty() {
return size() == 0;
}
/* 큐 삽입 연산 */
private void push(int num, boolean isFront) {
ListNode node = new ListNode(num);
// 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다
if (isEmpty())
front = rear = node;
// 맨 앞에 삽입하는 연산
else if (isFront) {
// node를 연결 리스트의 맨 앞에 추가한다
front.prev = node;
node.next = front;
front = node; // 머리 노드를 갱신한다
// 맨 뒤에 삽입하는 연산
} else {
// node를 연결 리스트의 맨 뒤에 추가한다
rear.next = node;
node.prev = rear;
rear = node; // 꼬리 노드를 갱신한다
}
queSize++; // 큐 길이를 갱신한다
}
/* 맨 앞에 삽입 */
public void pushFirst(int num) {
push(num, true);
}
/* 맨 뒤에 삽입 */
public void pushLast(int num) {
push(num, false);
}
/* 큐에서 꺼내는 연산 */
private int pop(boolean isFront) {
if (isEmpty())
throw new IndexOutOfBoundsException();
int val;
// 큐의 길이가 1이면 머리와 꼬리가 같은 노드를 가리킨다
if (queSize == 1) {
val = front.val;
front = null;
rear = null;
}
// 맨 앞에서 꺼내는 연산
else if (isFront) {
val = front.val; // 머리 노드의 값을 임시로 저장한다
// 머리 노드를 삭제한다
ListNode fNext = front.next;
fNext.prev = null;
front.next = null;
front = fNext; // 머리 노드를 갱신한다
// 맨 뒤에서 꺼내는 연산
} else {
val = rear.val; // 꼬리 노드의 값을 임시로 저장한다
// 꼬리 노드를 삭제한다
ListNode rPrev = rear.prev;
rPrev.next = null;
rear.prev = null;
rear = rPrev; // 꼬리 노드를 갱신한다
}
queSize--; // 큐 길이를 갱신한다
return val;
}
/* 맨 앞에서 꺼내기 */
public int popFirst() {
return pop(true);
}
/* 맨 뒤에서 꺼내기 */
public int popLast() {
return pop(false);
}
/* 맨 앞 원소 접근 */
public int peekFirst() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return front.val;
}
/* 맨 뒤 원소 접근 */
public int peekLast() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return rear.val;
}
/* 출력에 사용할 배열 반환 */
public int[] toArray() {
ListNode node = front;
int[] res = new int[size()];
for (int i = 0; i < res.length; i++) {
res[i] = node.val;
node = node.next;
}
return res;
}
}
public class linkedlist_deque {
public static void main(String[] args) {
/* 덱 초기화 */
LinkedListDeque deque = new LinkedListDeque();
deque.pushLast(3);
deque.pushLast(2);
deque.pushLast(5);
System.out.println("덱 deque = " + Arrays.toString(deque.toArray()));
/* 원소 접근 */
int peekFirst = deque.peekFirst();
System.out.println("맨 앞 원소 peekFirst = " + peekFirst);
int peekLast = deque.peekLast();
System.out.println("맨 뒤 원소 peekLast = " + peekLast);
/* 큐에 원소 삽입 */
deque.pushLast(4);
System.out.println("원소 4를 맨 뒤에 삽입한 후 deque = " + Arrays.toString(deque.toArray()));
deque.pushFirst(1);
System.out.println("원소 1을 맨 앞에 삽입한 후 deque = " + Arrays.toString(deque.toArray()));
/* 큐에서 원소 꺼내기 */
int popLast = deque.popLast();
System.out.println("맨 뒤에서 꺼낸 원소 = " + popLast + ", 맨 뒤에서 꺼낸 후 deque = " + Arrays.toString(deque.toArray()));
int popFirst = deque.popFirst();
System.out.println("맨 앞에서 꺼낸 원소 = " + popFirst + ", 맨 앞에서 꺼낸 후 deque = " + Arrays.toString(deque.toArray()));
/* 덱의 길이 반환 */
int size = deque.size();
System.out.println("덱 길이 size = " + size);
/* 덱이 비어 있는지 판단 */
boolean isEmpty = deque.isEmpty();
System.out.println("덱이 비어 있는가 = " + isEmpty);
}
}

View File

@@ -0,0 +1,104 @@
/**
* File: linkedlist_queue.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_stack_and_queue;
import java.util.*;
/* 연결 리스트로 구현한 큐 */
class LinkedListQueue {
private ListNode front, rear; // 머리 노드 front, 꼬리 노드 rear
private int queSize = 0;
public LinkedListQueue() {
front = null;
rear = null;
}
/* 큐의 길이 반환 */
public int size() {
return queSize;
}
/* 큐가 비어 있는지 판단 */
public boolean isEmpty() {
return size() == 0;
}
/* 큐에 삽입 */
public void push(int num) {
// 꼬리 노드 뒤에 num을 추가한다
ListNode node = new ListNode(num);
// 큐가 비어 있으면 머리와 꼬리 노드가 모두 해당 노드를 가리키게 한다
if (front == null) {
front = node;
rear = node;
// 큐가 비어 있지 않으면 해당 노드를 꼬리 노드 뒤에 추가한다
} else {
rear.next = node;
rear = node;
}
queSize++;
}
/* 큐에서 꺼내기 */
public int pop() {
int num = peek();
// 머리 노드를 삭제한다
front = front.next;
queSize--;
return num;
}
/* 맨 앞 원소 접근 */
public int peek() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return front.val;
}
/* 연결 리스트를 Array로 변환하여 반환 */
public int[] toArray() {
ListNode node = front;
int[] res = new int[size()];
for (int i = 0; i < res.length; i++) {
res[i] = node.val;
node = node.next;
}
return res;
}
}
public class linkedlist_queue {
public static void main(String[] args) {
/* 큐 초기화 */
LinkedListQueue queue = new LinkedListQueue();
/* 큐에 원소 삽입 */
queue.push(1);
queue.push(3);
queue.push(2);
queue.push(5);
queue.push(4);
System.out.println("큐 queue = " + Arrays.toString(queue.toArray()));
/* 맨 앞 원소 접근 */
int peek = queue.peek();
System.out.println("맨 앞 원소 peek = " + peek);
/* 큐에서 원소 꺼내기 */
int pop = queue.pop();
System.out.println("큐에서 꺼낸 원소 pop = " + pop + ", 큐에서 꺼낸 후 queue = " + Arrays.toString(queue.toArray()));
/* 큐의 길이 반환 */
int size = queue.size();
System.out.println("큐 길이 size = " + size);
/* 큐가 비어 있는지 판단 */
boolean isEmpty = queue.isEmpty();
System.out.println("큐가 비어 있는가 = " + isEmpty);
}
}

View File

@@ -0,0 +1,95 @@
/**
* File: linkedlist_stack.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_stack_and_queue;
import java.util.*;
import utils.*;
/* 연결 리스트로 구현한 스택 */
class LinkedListStack {
private ListNode stackPeek; // 머리 노드를 스택의 맨 위로 사용한다
private int stkSize = 0; // 스택의 길이
public LinkedListStack() {
stackPeek = null;
}
/* 스택의 길이 반환 */
public int size() {
return stkSize;
}
/* 스택이 비어 있는지 판단 */
public boolean isEmpty() {
return size() == 0;
}
/* 스택에 삽입 */
public void push(int num) {
ListNode node = new ListNode(num);
node.next = stackPeek;
stackPeek = node;
stkSize++;
}
/* 스택에서 꺼내기 */
public int pop() {
int num = peek();
stackPeek = stackPeek.next;
stkSize--;
return num;
}
/* 스택 맨 위 원소 접근 */
public int peek() {
if (isEmpty())
throw new IndexOutOfBoundsException();
return stackPeek.val;
}
/* List를 Array로 변환하여 반환 */
public int[] toArray() {
ListNode node = stackPeek;
int[] res = new int[size()];
for (int i = res.length - 1; i >= 0; i--) {
res[i] = node.val;
node = node.next;
}
return res;
}
}
public class linkedlist_stack {
public static void main(String[] args) {
/* 스택 초기화 */
LinkedListStack stack = new LinkedListStack();
/* 스택에 원소 삽입 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
System.out.println("스택 stack = " + Arrays.toString(stack.toArray()));
/* 스택 맨 위 원소 접근 */
int peek = stack.peek();
System.out.println("스택 맨 위 원소 peek = " + peek);
/* 스택에서 원소 꺼내기 */
int pop = stack.pop();
System.out.println("스택에서 꺼낸 원소 pop = " + pop + ", 스택에서 꺼낸 후 stack = " + Arrays.toString(stack.toArray()));
/* 스택의 길이 반환 */
int size = stack.size();
System.out.println("스택의 길이 size = " + size);
/* 비어 있는지 판단 */
boolean isEmpty = stack.isEmpty();
System.out.println("스택이 비어 있는가 = " + isEmpty);
}
}

View File

@@ -0,0 +1,40 @@
/**
* File: queue.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_stack_and_queue;
import java.util.*;
public class queue {
public static void main(String[] args) {
/* 큐 초기화 */
Queue<Integer> queue = new LinkedList<>();
/* 큐에 원소 삽입 */
queue.offer(1);
queue.offer(3);
queue.offer(2);
queue.offer(5);
queue.offer(4);
System.out.println("큐 queue = " + queue);
/* 맨 앞 원소 접근 */
int peek = queue.peek();
System.out.println("맨 앞 원소 peek = " + peek);
/* 큐에서 원소 꺼내기 */
int pop = queue.poll();
System.out.println("큐에서 꺼낸 원소 pop = " + pop + ", 큐에서 꺼낸 후 queue = " + queue);
/* 큐의 길이 반환 */
int size = queue.size();
System.out.println("큐 길이 size = " + size);
/* 큐가 비어 있는지 판단 */
boolean isEmpty = queue.isEmpty();
System.out.println("큐가 비어 있는가 = " + isEmpty);
}
}

View File

@@ -0,0 +1,40 @@
/**
* File: stack.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_stack_and_queue;
import java.util.*;
public class stack {
public static void main(String[] args) {
/* 스택 초기화 */
Stack<Integer> stack = new Stack<>();
/* 스택에 원소 삽입 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
System.out.println("스택 stack = " + stack);
/* 스택 맨 위 원소 접근 */
int peek = stack.peek();
System.out.println("스택 맨 위 원소 peek = " + peek);
/* 스택에서 원소 꺼내기 */
int pop = stack.pop();
System.out.println("스택에서 꺼낸 원소 pop = " + pop + ", 스택에서 꺼낸 후 stack = " + stack);
/* 스택의 길이 반환 */
int size = stack.size();
System.out.println("스택의 길이 size = " + size);
/* 비어 있는지 판단 */
boolean isEmpty = stack.isEmpty();
System.out.println("스택이 비어 있는가 = " + isEmpty);
}
}

View File

@@ -0,0 +1,136 @@
/**
* File: array_binary_tree.java
* Created Time: 2023-07-19
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
import java.util.*;
/* 배열로 표현한 이진 트리 클래스 */
class ArrayBinaryTree {
private List<Integer> tree;
/* 생성자 */
public ArrayBinaryTree(List<Integer> arr) {
tree = new ArrayList<>(arr);
}
/* 리스트 용량 */
public int size() {
return tree.size();
}
/* 인덱스가 i인 노드의 값 반환 */
public Integer val(int i) {
// 인덱스가 범위를 벗어나면 빈칸을 나타내는 null을 반환한다
if (i < 0 || i >= size())
return null;
return tree.get(i);
}
/* 인덱스가 i인 노드의 왼쪽 자식 노드 인덱스 반환 */
public Integer left(int i) {
return 2 * i + 1;
}
/* 인덱스가 i인 노드의 오른쪽 자식 노드 인덱스 반환 */
public Integer right(int i) {
return 2 * i + 2;
}
/* 인덱스가 i인 노드의 부모 노드 인덱스 반환 */
public Integer parent(int i) {
return (i - 1) / 2;
}
/* 레벨 순서 순회 */
public List<Integer> levelOrder() {
List<Integer> res = new ArrayList<>();
// 배열을 직접 순회한다
for (int i = 0; i < size(); i++) {
if (val(i) != null)
res.add(val(i));
}
return res;
}
/* 깊이 우선 순회 */
private void dfs(Integer i, String order, List<Integer> res) {
// 빈칸이면 반환한다
if (val(i) == null)
return;
// 전위 순회
if ("pre".equals(order))
res.add(val(i));
dfs(left(i), order, res);
// 중위 순회
if ("in".equals(order))
res.add(val(i));
dfs(right(i), order, res);
// 후위 순회
if ("post".equals(order))
res.add(val(i));
}
/* 전위 순회 */
public List<Integer> preOrder() {
List<Integer> res = new ArrayList<>();
dfs(0, "pre", res);
return res;
}
/* 중위 순회 */
public List<Integer> inOrder() {
List<Integer> res = new ArrayList<>();
dfs(0, "in", res);
return res;
}
/* 후위 순회 */
public List<Integer> postOrder() {
List<Integer> res = new ArrayList<>();
dfs(0, "post", res);
return res;
}
}
public class array_binary_tree {
public static void main(String[] args) {
// 이진 트리 초기화
// 여기서는 배열로부터 이진 트리를 바로 생성하는 함수를 사용한다
List<Integer> arr = Arrays.asList(1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15);
TreeNode root = TreeNode.listToTree(arr);
System.out.println("\n이진 트리 초기화\n");
System.out.println("이진 트리의 배열 표현:");
System.out.println(arr);
System.out.println("이진 트리의 연결 리스트 표현:");
PrintUtil.printTree(root);
// 배열로 표현한 이진 트리 클래스
ArrayBinaryTree abt = new ArrayBinaryTree(arr);
// 노드 접근
int i = 1;
Integer l = abt.left(i);
Integer r = abt.right(i);
Integer p = abt.parent(i);
System.out.println("\n현재 노드의 인덱스: " + i + " , 값: " + abt.val(i));
System.out.println("왼쪽 자식 노드의 인덱스: " + l + " , 값: " + (l == null ? "null" : abt.val(l)));
System.out.println("오른쪽 자식 노드의 인덱스: " + r + " , 값: " + (r == null ? "null" : abt.val(r)));
System.out.println("부모 노드의 인덱스: " + p + " , 값: " + (p == null ? "null" : abt.val(p)));
// 트리 순회
List<Integer> res = abt.levelOrder();
System.out.println("\n레벨 순서 순회:" + res);
res = abt.preOrder();
System.out.println("전위 순회:" + res);
res = abt.inOrder();
System.out.println("중위 순회:" + res);
res = abt.postOrder();
System.out.println("후위 순회:" + res);
}
}

View File

@@ -0,0 +1,220 @@
/**
* File: avl_tree.java
* Created Time: 2022-12-10
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
/* AVL 트리 */
class AVLTree {
TreeNode root; // 루트 노드
/* 노드 높이 반환 */
public int height(TreeNode node) {
// 빈 노드의 높이는 -1이고, 리프 노드의 높이는 0이다
return node == null ? -1 : node.height;
}
/* 노드 높이를 갱신한다 */
private void updateHeight(TreeNode node) {
// 노드 높이는 가장 높은 서브트리의 높이 + 1이다
node.height = Math.max(height(node.left), height(node.right)) + 1;
}
/* 균형 인수 반환 */
public int balanceFactor(TreeNode node) {
// 빈 노드의 균형 인수는 0이다
if (node == null)
return 0;
// 노드의 균형 인수 = 왼쪽 서브트리 높이 - 오른쪽 서브트리 높이
return height(node.left) - height(node.right);
}
/* 오른쪽 회전 연산 */
private TreeNode rightRotate(TreeNode node) {
TreeNode child = node.left;
TreeNode grandChild = child.right;
// child를 중심으로 node를 오른쪽으로 회전한다
child.right = node;
node.left = grandChild;
// 노드 높이를 갱신한다
updateHeight(node);
updateHeight(child);
// 회전한 서브트리의 루트 노드를 반환한다
return child;
}
/* 왼쪽 회전 연산 */
private TreeNode leftRotate(TreeNode node) {
TreeNode child = node.right;
TreeNode grandChild = child.left;
// child를 중심으로 node를 왼쪽으로 회전한다
child.left = node;
node.right = grandChild;
// 노드 높이를 갱신한다
updateHeight(node);
updateHeight(child);
// 회전한 서브트리의 루트 노드를 반환한다
return child;
}
/* 회전 연산을 수행하여 해당 서브트리의 균형 복원 */
private TreeNode rotate(TreeNode node) {
// 노드 node의 균형 인수를 구한다
int balanceFactor = balanceFactor(node);
// 왼쪽으로 치우친 트리
if (balanceFactor > 1) {
if (balanceFactor(node.left) >= 0) {
// 오른쪽 회전
return rightRotate(node);
} else {
// 왼쪽으로 회전한 후 오른쪽으로 회전한다
node.left = leftRotate(node.left);
return rightRotate(node);
}
}
// 오른쪽으로 치우친 트리
if (balanceFactor < -1) {
if (balanceFactor(node.right) <= 0) {
// 왼쪽 회전
return leftRotate(node);
} else {
// 오른쪽으로 회전한 후 왼쪽으로 회전한다
node.right = rightRotate(node.right);
return leftRotate(node);
}
}
// 균형 트리이므로 회전할 필요 없이 바로 반환한다
return node;
}
/* 노드 삽입 */
public void insert(int val) {
root = insertHelper(root, val);
}
/* 노드의 재귀적 삽입(보조 메서드) */
private TreeNode insertHelper(TreeNode node, int val) {
if (node == null)
return new TreeNode(val);
/* 1. 삽입 위치를 찾아 노드를 삽입한다 */
if (val < node.val)
node.left = insertHelper(node.left, val);
else if (val > node.val)
node.right = insertHelper(node.right, val);
else
return node; // 중복 노드는 삽입하지 않고 바로 반환한다
updateHeight(node); // 노드 높이를 갱신한다
/* 2. 회전 연산을 수행하여 해당 서브트리의 균형을 복원한다 */
node = rotate(node);
// 서브트리의 루트 노드를 반환한다
return node;
}
/* 노드 삭제 */
public void remove(int val) {
root = removeHelper(root, val);
}
/* 노드의 재귀적 삭제(보조 메서드) */
private TreeNode removeHelper(TreeNode node, int val) {
if (node == null)
return null;
/* 1. 노드를 찾아 삭제한다 */
if (val < node.val)
node.left = removeHelper(node.left, val);
else if (val > node.val)
node.right = removeHelper(node.right, val);
else {
if (node.left == null || node.right == null) {
TreeNode child = node.left != null ? node.left : node.right;
// 자식 노드 수 = 0이면 node를 바로 삭제하고 반환한다
if (child == null)
return null;
// 자식 노드 수 = 1이면 node를 바로 삭제한다
else
node = child;
} else {
// 자식 노드 수 = 2이면 중위 순회의 다음 노드를 삭제하고, 그 노드로 현재 노드를 대체한다
TreeNode temp = node.right;
while (temp.left != null) {
temp = temp.left;
}
node.right = removeHelper(node.right, temp.val);
node.val = temp.val;
}
}
updateHeight(node); // 노드 높이를 갱신한다
/* 2. 회전 연산을 수행하여 해당 서브트리의 균형을 복원한다 */
node = rotate(node);
// 서브트리의 루트 노드를 반환한다
return node;
}
/* 노드 탐색 */
public TreeNode search(int val) {
TreeNode cur = root;
// 반복하여 탐색하다 리프 노드를 지나면 종료한다
while (cur != null) {
// 목표 노드는 cur의 오른쪽 서브트리에 있다
if (cur.val < val)
cur = cur.right;
// 목표 노드는 cur의 왼쪽 서브트리에 있다
else if (cur.val > val)
cur = cur.left;
// 목표 노드를 찾았으므로 반복문을 종료한다
else
break;
}
// 목표 노드를 반환한다
return cur;
}
}
public class avl_tree {
static void testInsert(AVLTree tree, int val) {
tree.insert(val);
System.out.println("\n노드 삽입: " + val + " ; 연산 후 AVL 트리");
PrintUtil.printTree(tree.root);
}
static void testRemove(AVLTree tree, int val) {
tree.remove(val);
System.out.println("\n노드 삭제: " + val + " ; 연산 후 AVL 트리");
PrintUtil.printTree(tree.root);
}
public static void main(String[] args) {
/* 빈 AVL 트리 초기화 */
AVLTree avlTree = new AVLTree();
/* 노드 삽입 */
// 노드를 삽입한 후 AVL 트리가 어떻게 균형을 유지하는지 살펴본다
testInsert(avlTree, 1);
testInsert(avlTree, 2);
testInsert(avlTree, 3);
testInsert(avlTree, 4);
testInsert(avlTree, 5);
testInsert(avlTree, 8);
testInsert(avlTree, 7);
testInsert(avlTree, 9);
testInsert(avlTree, 10);
testInsert(avlTree, 6);
/* 중복 노드 삽입 */
testInsert(avlTree, 7);
/* 노드 삭제 */
// 노드를 삭제한 후 AVL 트리가 어떻게 균형을 유지하는지 살펴본다
testRemove(avlTree, 8); // 차수가 0인 노드 삭제
testRemove(avlTree, 5); // 차수가 1인 노드 삭제
testRemove(avlTree, 4); // 차수가 2인 노드 삭제
/* 노드 조회 */
TreeNode node = avlTree.search(7);
System.out.println("\n찾은 노드 객체: " + node + ", 노드 값 = " + node.val);
}
}

View File

@@ -0,0 +1,158 @@
/**
* File: binary_search_tree.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
/* 이진 탐색 트리 */
class BinarySearchTree {
private TreeNode root;
/* 생성자 */
public BinarySearchTree() {
// 빈 트리를 초기화한다
root = null;
}
/* 이진 트리의 루트 노드 반환 */
public TreeNode getRoot() {
return root;
}
/* 노드 탐색 */
public TreeNode search(int num) {
TreeNode cur = root;
// 반복하여 탐색하다 리프 노드를 지나면 종료한다
while (cur != null) {
// 목표 노드는 cur의 오른쪽 서브트리에 있다
if (cur.val < num)
cur = cur.right;
// 목표 노드는 cur의 왼쪽 서브트리에 있다
else if (cur.val > num)
cur = cur.left;
// 목표 노드를 찾았으므로 반복문을 종료한다
else
break;
}
// 목표 노드를 반환한다
return cur;
}
/* 노드 삽입 */
public void insert(int num) {
// 트리가 비어 있으면 루트 노드를 초기화한다
if (root == null) {
root = new TreeNode(num);
return;
}
TreeNode cur = root, pre = null;
// 반복하여 탐색하다 리프 노드를 지나면 종료한다
while (cur != null) {
// 중복 노드를 찾으면 바로 반환한다
if (cur.val == num)
return;
pre = cur;
// 삽입 위치는 cur의 오른쪽 서브트리에 있다
if (cur.val < num)
cur = cur.right;
// 삽입 위치는 cur의 왼쪽 서브트리에 있다
else
cur = cur.left;
}
// 노드 삽입
TreeNode node = new TreeNode(num);
if (pre.val < num)
pre.right = node;
else
pre.left = node;
}
/* 노드 삭제 */
public void remove(int num) {
// 트리가 비어 있으면 바로 반환하여 종료한다
if (root == null)
return;
TreeNode cur = root, pre = null;
// 반복하여 탐색하다 리프 노드를 지나면 종료한다
while (cur != null) {
// 삭제할 노드를 찾았으므로 반복문을 종료한다
if (cur.val == num)
break;
pre = cur;
// 삭제할 노드는 cur의 오른쪽 서브트리에 있다
if (cur.val < num)
cur = cur.right;
// 삭제할 노드는 cur의 왼쪽 서브트리에 있다
else
cur = cur.left;
}
// 삭제할 노드가 없으면 바로 반환한다
if (cur == null)
return;
// 자식 노드 수 = 0 또는 1
if (cur.left == null || cur.right == null) {
// 자식 노드 수 = 0 / 1이면 child = null / 해당 자식 노드이다
TreeNode child = cur.left != null ? cur.left : cur.right;
// 노드 cur를 삭제한다
if (cur != root) {
if (pre.left == cur)
pre.left = child;
else
pre.right = child;
} else {
// 삭제할 노드가 루트 노드이면 루트 노드를 다시 지정한다
root = child;
}
}
// 자식 노드 수 = 2
else {
// 중위 순회에서 cur의 다음 노드를 구한다
TreeNode tmp = cur.right;
while (tmp.left != null) {
tmp = tmp.left;
}
// 노드 tmp를 재귀적으로 삭제한다
remove(tmp.val);
// tmp로 cur를 덮어쓴다
cur.val = tmp.val;
}
}
}
public class binary_search_tree {
public static void main(String[] args) {
/* 이진 탐색 트리 초기화 */
BinarySearchTree bst = new BinarySearchTree();
// 삽입 순서에 따라 서로 다른 이진 트리가 생성된다. 이 순서는 포화 이진 트리를 생성할 수 있다
int[] nums = { 8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15 };
for (int num : nums) {
bst.insert(num);
}
System.out.println("\n초기화한 이진 트리\n");
PrintUtil.printTree(bst.getRoot());
/* 노드 탐색 */
TreeNode node = bst.search(7);
System.out.println("\n찾은 노드 객체: " + node + ", 노드 값 = " + node.val);
/* 노드 삽입 */
bst.insert(16);
System.out.println("\n노드 16을 삽입한 후의 이진 트리\n");
PrintUtil.printTree(bst.getRoot());
/* 노드 삭제 */
bst.remove(1);
System.out.println("\n노드 1을 삭제한 후의 이진 트리\n");
PrintUtil.printTree(bst.getRoot());
bst.remove(2);
System.out.println("\n노드 2를 삭제한 후의 이진 트리\n");
PrintUtil.printTree(bst.getRoot());
bst.remove(4);
System.out.println("\n노드 4를 삭제한 후의 이진 트리\n");
PrintUtil.printTree(bst.getRoot());
}
}

View File

@@ -0,0 +1,40 @@
/**
* File: binary_tree.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
public class binary_tree {
public static void main(String[] args) {
/* 이진 트리 초기화 */
// 노드 초기화
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
// 노드 사이의 참조(포인터)를 설정한다
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
System.out.println("\n이진 트리 초기화\n");
PrintUtil.printTree(n1);
/* 노드 삽입과 삭제 */
TreeNode P = new TreeNode(0);
// n1 -> n2 사이에 노드 P를 삽입한다
n1.left = P;
P.left = n2;
System.out.println("\n노드 P를 삽입한 후\n");
PrintUtil.printTree(n1);
// 노드 P를 삭제한다
n1.left = n2;
System.out.println("\n노드 P를 삭제한 후\n");
PrintUtil.printTree(n1);
}
}

View File

@@ -0,0 +1,42 @@
/**
* File: binary_tree_bfs.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
import java.util.*;
public class binary_tree_bfs {
/* 레벨 순서 순회 */
static List<Integer> levelOrder(TreeNode root) {
// 큐를 초기화하고 루트 노드를 넣는다
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
// 순회 순서를 저장할 리스트를 초기화한다
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll(); // 큐에서 꺼낸다
list.add(node.val); // 노드 값을 저장한다
if (node.left != null)
queue.offer(node.left); // 왼쪽 자식 노드를 큐에 삽입한다
if (node.right != null)
queue.offer(node.right); // 오른쪽 자식 노드를 큐에 삽입한다
}
return list;
}
public static void main(String[] args) {
/* 이진 트리 초기화 */
// 여기서는 배열로부터 이진 트리를 바로 생성하는 함수를 사용한다
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
System.out.println("\n이진 트리 초기화\n");
PrintUtil.printTree(root);
/* 레벨 순서 순회 */
List<Integer> list = levelOrder(root);
System.out.println("\n레벨 순서 순회의 노드 출력 순서 = " + list);
}
}

View File

@@ -0,0 +1,68 @@
/**
* File: binary_tree_dfs.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package chapter_tree;
import utils.*;
import java.util.*;
public class binary_tree_dfs {
// 순회 순서를 저장할 리스트를 초기화한다
static ArrayList<Integer> list = new ArrayList<>();
/* 전위 순회 */
static void preOrder(TreeNode root) {
if (root == null)
return;
// 방문 우선순위: 루트 노드 -> 왼쪽 서브트리 -> 오른쪽 서브트리
list.add(root.val);
preOrder(root.left);
preOrder(root.right);
}
/* 중위 순회 */
static void inOrder(TreeNode root) {
if (root == null)
return;
// 방문 우선순위: 왼쪽 서브트리 -> 루트 노드 -> 오른쪽 서브트리
inOrder(root.left);
list.add(root.val);
inOrder(root.right);
}
/* 후위 순회 */
static void postOrder(TreeNode root) {
if (root == null)
return;
// 방문 우선순위: 왼쪽 서브트리 -> 오른쪽 서브트리 -> 루트 노드
postOrder(root.left);
postOrder(root.right);
list.add(root.val);
}
public static void main(String[] args) {
/* 이진 트리 초기화 */
// 여기서는 배열로부터 이진 트리를 바로 생성하는 함수를 사용한다
TreeNode root = TreeNode.listToTree(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
System.out.println("\n이진 트리 초기화\n");
PrintUtil.printTree(root);
/* 전위 순회 */
list.clear();
preOrder(root);
System.out.println("\n전위 순회의 노드 출력 순서 = " + list);
/* 중위 순회 */
list.clear();
inOrder(root);
System.out.println("\n중위 순회의 노드 출력 순서 = " + list);
/* 후위 순회 */
list.clear();
postOrder(root);
System.out.println("\n후위 순회의 노드 출력 순서 = " + list);
}
}

View File

@@ -0,0 +1,28 @@
/**
* File: ListNode.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package utils;
/* 연결 리스트 노드 */
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
}
/* 리스트를 연결 리스트로 역직렬화 */
public static ListNode arrToLinkedList(int[] arr) {
ListNode dum = new ListNode(0);
ListNode head = dum;
for (int val : arr) {
head.next = new ListNode(val);
head = head.next;
}
return dum.next;
}
}

View File

@@ -0,0 +1,116 @@
/**
* File: PrintUtil.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package utils;
import java.util.*;
class Trunk {
Trunk prev;
String str;
Trunk(Trunk prev, String str) {
this.prev = prev;
this.str = str;
}
};
public class PrintUtil {
/* 행렬 출력(Array) */
public static <T> void printMatrix(T[][] matrix) {
System.out.println("[");
for (T[] row : matrix) {
System.out.println(" " + row + ",");
}
System.out.println("]");
}
/* 행렬 출력(List) */
public static <T> void printMatrix(List<List<T>> matrix) {
System.out.println("[");
for (List<T> row : matrix) {
System.out.println(" " + row + ",");
}
System.out.println("]");
}
/* 연결 리스트 출력 */
public static void printLinkedList(ListNode head) {
List<String> list = new ArrayList<>();
while (head != null) {
list.add(String.valueOf(head.val));
head = head.next;
}
System.out.println(String.join(" -> ", list));
}
/* 이진 트리 출력 */
public static void printTree(TreeNode root) {
printTree(root, null, false);
}
/**
* 이진 트리 출력
* 이 트리 출력 코드는 TECHIE DELIGHT에서 가져왔다
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
public static void printTree(TreeNode root, Trunk prev, boolean isRight) {
if (root == null) {
return;
}
String prev_str = " ";
Trunk trunk = new Trunk(prev, prev_str);
printTree(root.right, trunk, true);
if (prev == null) {
trunk.str = "———";
} else if (isRight) {
trunk.str = "/———";
prev_str = " |";
} else {
trunk.str = "\\———";
prev.str = prev_str;
}
showTrunks(trunk);
System.out.println(" " + root.val);
if (prev != null) {
prev.str = prev_str;
}
trunk.str = " |";
printTree(root.left, trunk, false);
}
public static void showTrunks(Trunk p) {
if (p == null) {
return;
}
showTrunks(p.prev);
System.out.print(p.str);
}
/* 해시 테이블 출력 */
public static <K, V> void printHashMap(Map<K, V> map) {
for (Map.Entry<K, V> kv : map.entrySet()) {
System.out.println(kv.getKey() + " -> " + kv.getValue());
}
}
/* 힙(우선순위 큐) 출력 */
public static void printHeap(Queue<Integer> queue) {
List<Integer> list = new ArrayList<>(queue);
System.out.print("힙의 배열 표현:");
System.out.println(list);
System.out.println("힙의 트리 표현:");
TreeNode root = TreeNode.listToTree(list);
printTree(root);
}
}

View File

@@ -0,0 +1,73 @@
/**
* File: TreeNode.java
* Created Time: 2022-11-25
* Author: krahets (krahets@163.com)
*/
package utils;
import java.util.*;
/* 이진 트리 노드 클래스 */
public class TreeNode {
public int val; // 노드 값
public int height; // 노드 높이
public TreeNode left; // 왼쪽 자식 노드 참조
public TreeNode right; // 오른쪽 자식 노드 참조
/* 생성자 */
public TreeNode(int x) {
val = x;
}
// 직렬화 인코딩 규칙은 다음을 참고한다:
// https://www.hello-algo.com/ko/chapter_tree/array_representation_of_tree/
// 이진 트리의 배열 표현:
// [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
// 이진 트리의 연결 리스트 표현:
// /——— 15
// /——— 7
// /——— 3
// | \——— 6
// | \——— 12
// ——— 1
// \——— 2
// | /——— 9
// \——— 4
// \——— 8
/* 리스트를 이진 트리로 역직렬화: 재귀 */
private static TreeNode listToTreeDFS(List<Integer> arr, int i) {
if (i < 0 || i >= arr.size() || arr.get(i) == null) {
return null;
}
TreeNode root = new TreeNode(arr.get(i));
root.left = listToTreeDFS(arr, 2 * i + 1);
root.right = listToTreeDFS(arr, 2 * i + 2);
return root;
}
/* 리스트를 이진 트리로 역직렬화 */
public static TreeNode listToTree(List<Integer> arr) {
return listToTreeDFS(arr, 0);
}
/* 이진 트리를 리스트로 직렬화: 재귀 */
private static void treeToListDFS(TreeNode root, int i, List<Integer> res) {
if (root == null)
return;
while (i >= res.size()) {
res.add(null);
}
res.set(i, root.val);
treeToListDFS(root.left, 2 * i + 1, res);
treeToListDFS(root.right, 2 * i + 2, res);
}
/* 이진 트리를 리스트로 직렬화 */
public static List<Integer> treeToList(TreeNode root) {
List<Integer> res = new ArrayList<>();
treeToListDFS(root, 0, res);
return res;
}
}

View File

@@ -0,0 +1,36 @@
/**
* File: Vertex.java
* Created Time: 2023-02-15
* Author: krahets (krahets@163.com)
*/
package utils;
import java.util.*;
/* 정점 클래스 */
public class Vertex {
public int val;
public Vertex(int val) {
this.val = val;
}
/* 값의 리스트 vals를 입력받아 정점 리스트 vets 반환 */
public static Vertex[] valsToVets(int[] vals) {
Vertex[] vets = new Vertex[vals.length];
for (int i = 0; i < vals.length; i++) {
vets[i] = new Vertex(vals[i]);
}
return vets;
}
/* 정점 리스트 vets를 입력받아 값의 리스트 vals 반환 */
public static List<Integer> vetsToVals(List<Vertex> vets) {
List<Integer> vals = new ArrayList<>();
for (Vertex vet : vets) {
vals.add(vet.val);
}
return vals;
}
}