mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-28 15:32:03 +08:00
feat(ko): add the Korean online edition (#2006)
* feat(ko): add the complete Korean online edition * Use UTF-8 for Python CI output on Windows * Remove print-book promotion from the Korean site * fix(ko): preserve emphasis before Korean particles
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* File: climbing_stairs_backtrack.cs
|
||||
* Created Time: 2023-06-30
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_backtrack {
|
||||
/* 백트래킹 */
|
||||
void Backtrack(List<int> choices, int state, int n, List<int> res) {
|
||||
// n번째 계단에 도달하면 방법의 수에 1을 더한다
|
||||
if (state == n)
|
||||
res[0]++;
|
||||
// 모든 선택지를 순회한다
|
||||
foreach (int choice in choices) {
|
||||
// 가지치기: n번째 계단을 넘어갈 수 없다
|
||||
if (state + choice > n)
|
||||
continue;
|
||||
// 시도: 선택하고 상태를 갱신한다
|
||||
Backtrack(choices, state + choice, n, res);
|
||||
// 되돌리기
|
||||
}
|
||||
}
|
||||
|
||||
/* 계단 오르기: 백트래킹 */
|
||||
int ClimbingStairsBacktrack(int n) {
|
||||
List<int> choices = [1, 2]; // 한 계단 또는 두 계단 오르기를 선택할 수 있다
|
||||
int state = 0; // 0번째 계단에서 오르기 시작한다
|
||||
List<int> res = [0]; // res[0]에 방법의 수를 기록한다
|
||||
Backtrack(choices, state, n, res);
|
||||
return res[0];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsBacktrack(n);
|
||||
Console.WriteLine($"{n}개의 계단을 오르는 방법은 총 {res}가지이다");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* File: climbing_stairs_constraint_dp.cs
|
||||
* Created Time: 2023-07-03
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_constraint_dp {
|
||||
/* 제약 조건이 있는 계단 오르기: 동적 계획법 */
|
||||
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];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsConstraintDP(n);
|
||||
Console.WriteLine($"{n}개의 계단을 오르는 방법은 총 {res}가지이다");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs.cs
|
||||
* Created Time: 2023-06-30
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_dfs {
|
||||
/* 탐색 */
|
||||
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;
|
||||
}
|
||||
|
||||
/* 계단 오르기: 탐색 */
|
||||
int ClimbingStairsDFS(int n) {
|
||||
return DFS(n);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsDFS(n);
|
||||
Console.WriteLine($"{n}개의 계단을 오르는 방법은 총 {res}가지이다");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs_mem.cs
|
||||
* Created Time: 2023-06-30
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_dfs_mem {
|
||||
/* 메모이제이션을 이용한 탐색 */
|
||||
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;
|
||||
}
|
||||
|
||||
/* 계단 오르기: 메모이제이션을 이용한 탐색 */
|
||||
int ClimbingStairsDFSMem(int n) {
|
||||
// mem[i]는 i번째 계단까지 오르는 전체 방법의 수를 기록하며, -1은 기록이 없음을 나타낸다
|
||||
int[] mem = new int[n + 1];
|
||||
Array.Fill(mem, -1);
|
||||
return DFS(n, mem);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
int res = ClimbingStairsDFSMem(n);
|
||||
Console.WriteLine($"{n}개의 계단을 오르는 방법은 총 {res}가지이다");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: climbing_stairs_dp.cs
|
||||
* Created Time: 2023-06-30
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class climbing_stairs_dp {
|
||||
/* 계단 오르기: 동적 계획법 */
|
||||
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];
|
||||
}
|
||||
|
||||
/* 계단 오르기: 공간을 최적화한 동적 계획법 */
|
||||
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;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int n = 9;
|
||||
|
||||
int res = ClimbingStairsDP(n);
|
||||
Console.WriteLine($"{n}개의 계단을 오르는 방법은 총 {res}가지이다");
|
||||
|
||||
res = ClimbingStairsDPComp(n);
|
||||
Console.WriteLine($"{n}개의 계단을 오르는 방법은 총 {res}가지이다");
|
||||
}
|
||||
}
|
||||
71
ko/codes/csharp/chapter_dynamic_programming/coin_change.cs
Normal file
71
ko/codes/csharp/chapter_dynamic_programming/coin_change.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* File: coin_change.cs
|
||||
* Created Time: 2023-07-12
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class coin_change {
|
||||
/* 동전 교환: 동적 계획법 */
|
||||
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;
|
||||
}
|
||||
|
||||
/* 동전 교환: 공간을 최적화한 동적 계획법 */
|
||||
int CoinChangeDPComp(int[] coins, int amt) {
|
||||
int n = coins.Length;
|
||||
int MAX = amt + 1;
|
||||
// dp 테이블을 초기화한다
|
||||
int[] dp = new int[amt + 1];
|
||||
Array.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;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] coins = [1, 2, 5];
|
||||
int amt = 4;
|
||||
|
||||
// 동적 계획법
|
||||
int res = CoinChangeDP(coins, amt);
|
||||
Console.WriteLine("목표 금액을 만드는 데 필요한 최소 동전 개수: " + res);
|
||||
|
||||
// 공간을 최적화한 동적 계획법
|
||||
res = CoinChangeDPComp(coins, amt);
|
||||
Console.WriteLine("목표 금액을 만드는 데 필요한 최소 동전 개수: " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* File: coin_change_ii.cs
|
||||
* Created Time: 2023-07-12
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class coin_change_ii {
|
||||
/* 동전 교환 II: 동적 계획법 */
|
||||
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: 공간을 최적화한 동적 계획법 */
|
||||
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];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] coins = [1, 2, 5];
|
||||
int amt = 5;
|
||||
|
||||
// 동적 계획법
|
||||
int res = CoinChangeIIDP(coins, amt);
|
||||
Console.WriteLine("목표 금액을 만드는 동전 조합의 수: " + res);
|
||||
|
||||
// 공간을 최적화한 동적 계획법
|
||||
res = CoinChangeIIDPComp(coins, amt);
|
||||
Console.WriteLine("목표 금액을 만드는 동전 조합의 수: " + res);
|
||||
}
|
||||
}
|
||||
141
ko/codes/csharp/chapter_dynamic_programming/edit_distance.cs
Normal file
141
ko/codes/csharp/chapter_dynamic_programming/edit_distance.cs
Normal file
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* File: edit_distance.cs
|
||||
* Created Time: 2023-07-14
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class edit_distance {
|
||||
/* 편집 거리: 완전 탐색 */
|
||||
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[i - 1] == t[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;
|
||||
}
|
||||
|
||||
/* 편집 거리: 메모이제이션을 이용한 탐색 */
|
||||
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[i - 1] == t[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];
|
||||
}
|
||||
|
||||
/* 편집 거리: 동적 계획법 */
|
||||
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[i - 1] == t[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];
|
||||
}
|
||||
|
||||
/* 편집 거리: 공간을 최적화한 동적 계획법 */
|
||||
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[i - 1] == t[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];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
string s = "bag";
|
||||
string t = "pack";
|
||||
int n = s.Length, m = t.Length;
|
||||
|
||||
// 완전 탐색
|
||||
int res = EditDistanceDFS(s, t, n, m);
|
||||
Console.WriteLine("변경: " + s + " → " + t + " 변경에 필요한 최소 편집 횟수: " + res + " 회");
|
||||
|
||||
// 메모이제이션을 이용한 탐색
|
||||
int[][] mem = new int[n + 1][];
|
||||
for (int i = 0; i <= n; i++) {
|
||||
mem[i] = new int[m + 1];
|
||||
Array.Fill(mem[i], -1);
|
||||
}
|
||||
|
||||
res = EditDistanceDFSMem(s, t, mem, n, m);
|
||||
Console.WriteLine("변경: " + s + " → " + t + " 변경에 필요한 최소 편집 횟수: " + res + " 회");
|
||||
|
||||
// 동적 계획법
|
||||
res = EditDistanceDP(s, t);
|
||||
Console.WriteLine("변경: " + s + " → " + t + " 변경에 필요한 최소 편집 횟수: " + res + " 회");
|
||||
|
||||
// 공간을 최적화한 동적 계획법
|
||||
res = EditDistanceDPComp(s, t);
|
||||
Console.WriteLine("변경: " + s + " → " + t + " 변경에 필요한 최소 편집 횟수: " + res + " 회");
|
||||
}
|
||||
}
|
||||
118
ko/codes/csharp/chapter_dynamic_programming/knapsack.cs
Normal file
118
ko/codes/csharp/chapter_dynamic_programming/knapsack.cs
Normal file
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* File: knapsack.cs
|
||||
* Created Time: 2023-07-07
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class knapsack {
|
||||
/* 0-1 배낭: 완전 탐색 */
|
||||
int KnapsackDFS(int[] weight, int[] val, int i, int c) {
|
||||
// 모든 물건의 선택을 마쳤거나 배낭에 남은 용량이 없으면 가치 0을 반환한다
|
||||
if (i == 0 || c == 0) {
|
||||
return 0;
|
||||
}
|
||||
// 배낭 용량을 초과하면 배낭에 넣지 않는 선택만 가능하다
|
||||
if (weight[i - 1] > c) {
|
||||
return KnapsackDFS(weight, val, i - 1, c);
|
||||
}
|
||||
// 물건 i를 넣지 않는 경우와 넣는 경우의 최대 가치를 계산한다
|
||||
int no = KnapsackDFS(weight, val, i - 1, c);
|
||||
int yes = KnapsackDFS(weight, val, i - 1, c - weight[i - 1]) + val[i - 1];
|
||||
// 두 경우 중 더 큰 가치를 반환한다
|
||||
return Math.Max(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 배낭: 메모이제이션을 이용한 탐색 */
|
||||
int KnapsackDFSMem(int[] weight, 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 (weight[i - 1] > c) {
|
||||
return KnapsackDFSMem(weight, val, mem, i - 1, c);
|
||||
}
|
||||
// 물건 i를 넣지 않는 경우와 넣는 경우의 최대 가치를 계산한다
|
||||
int no = KnapsackDFSMem(weight, val, mem, i - 1, c);
|
||||
int yes = KnapsackDFSMem(weight, val, mem, i - 1, c - weight[i - 1]) + val[i - 1];
|
||||
// 두 경우 중 더 큰 가치를 기록하고 반환한다
|
||||
mem[i][c] = Math.Max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
/* 0-1 배낭: 동적 계획법 */
|
||||
int KnapsackDP(int[] weight, int[] val, int cap) {
|
||||
int n = weight.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 (weight[i - 1] > c) {
|
||||
// 배낭 용량을 초과하면 물건 i를 선택하지 않는다
|
||||
dp[i, c] = dp[i - 1, c];
|
||||
} else {
|
||||
// 물건 i를 선택하지 않는 경우와 선택하는 경우 중 더 큰 값
|
||||
dp[i, c] = Math.Max(dp[i - 1, c - weight[i - 1]] + val[i - 1], dp[i - 1, c]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n, cap];
|
||||
}
|
||||
|
||||
/* 0-1 배낭: 공간을 최적화한 동적 계획법 */
|
||||
int KnapsackDPComp(int[] weight, int[] val, int cap) {
|
||||
int n = weight.Length;
|
||||
// dp 테이블을 초기화한다
|
||||
int[] dp = new int[cap + 1];
|
||||
// 상태 전이
|
||||
for (int i = 1; i <= n; i++) {
|
||||
// 역방향 순회
|
||||
for (int c = cap; c > 0; c--) {
|
||||
if (weight[i - 1] > c) {
|
||||
// 배낭 용량을 초과하면 물건 i를 선택하지 않는다
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// 물건 i를 선택하지 않는 경우와 선택하는 경우 중 더 큰 값
|
||||
dp[c] = Math.Max(dp[c], dp[c - weight[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] weight = [10, 20, 30, 40, 50];
|
||||
int[] val = [50, 120, 150, 210, 240];
|
||||
int cap = 50;
|
||||
int n = weight.Length;
|
||||
|
||||
// 완전 탐색
|
||||
int res = KnapsackDFS(weight, val, n, cap);
|
||||
Console.WriteLine("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
|
||||
|
||||
// 메모이제이션을 이용한 탐색
|
||||
int[][] mem = new int[n + 1][];
|
||||
for (int i = 0; i <= n; i++) {
|
||||
mem[i] = new int[cap + 1];
|
||||
Array.Fill(mem[i], -1);
|
||||
}
|
||||
res = KnapsackDFSMem(weight, val, mem, n, cap);
|
||||
Console.WriteLine("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
|
||||
|
||||
// 동적 계획법
|
||||
res = KnapsackDP(weight, val, cap);
|
||||
Console.WriteLine("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
|
||||
|
||||
// 공간을 최적화한 동적 계획법
|
||||
res = KnapsackDPComp(weight, val, cap);
|
||||
Console.WriteLine("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* File: min_cost_climbing_stairs_dp.cs
|
||||
* Created Time: 2023-06-30
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class min_cost_climbing_stairs_dp {
|
||||
/* 계단 오르기의 최소 비용: 동적 계획법 */
|
||||
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];
|
||||
}
|
||||
|
||||
/* 계단 오르기의 최소 비용: 공간을 최적화한 동적 계획법 */
|
||||
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;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
|
||||
Console.WriteLine("입력한 계단의 비용 리스트:");
|
||||
PrintUtil.PrintList(cost);
|
||||
|
||||
int res = MinCostClimbingStairsDP(cost);
|
||||
Console.WriteLine($"계단을 모두 오르는 최소 비용은 {res}이다");
|
||||
|
||||
res = MinCostClimbingStairsDPComp(cost);
|
||||
Console.WriteLine($"계단을 모두 오르는 최소 비용은 {res}이다");
|
||||
}
|
||||
}
|
||||
127
ko/codes/csharp/chapter_dynamic_programming/min_path_sum.cs
Normal file
127
ko/codes/csharp/chapter_dynamic_programming/min_path_sum.cs
Normal file
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* File: min_path_sum.cs
|
||||
* Created Time: 2023-07-10
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class min_path_sum {
|
||||
/* 최소 경로 합: 완전 탐색 */
|
||||
int MinPathSumDFS(int[][] grid, int i, int j) {
|
||||
// 왼쪽 위 모서리의 칸이면 탐색을 종료한다
|
||||
if (i == 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// 행 또는 열 인덱스가 범위를 벗어나면 비용 +∞를 반환한다
|
||||
if (i < 0 || j < 0) {
|
||||
return int.MaxValue;
|
||||
}
|
||||
// 왼쪽 위 모서리에서 (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];
|
||||
}
|
||||
|
||||
/* 최소 경로 합: 메모이제이션을 이용한 탐색 */
|
||||
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 int.MaxValue;
|
||||
}
|
||||
// 기록이 이미 있으면 바로 반환한다
|
||||
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];
|
||||
}
|
||||
|
||||
/* 최소 경로 합: 동적 계획법 */
|
||||
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];
|
||||
}
|
||||
|
||||
/* 최소 경로 합: 공간을 최적화한 동적 계획법 */
|
||||
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];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
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);
|
||||
Console.WriteLine("왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: " + res);
|
||||
|
||||
// 메모이제이션을 이용한 탐색
|
||||
int[][] mem = new int[n][];
|
||||
for (int i = 0; i < n; i++) {
|
||||
mem[i] = new int[m];
|
||||
Array.Fill(mem[i], -1);
|
||||
}
|
||||
res = MinPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
Console.WriteLine("왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: " + res);
|
||||
|
||||
// 동적 계획법
|
||||
res = MinPathSumDP(grid);
|
||||
Console.WriteLine("왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: " + res);
|
||||
|
||||
// 공간을 최적화한 동적 계획법
|
||||
res = MinPathSumDPComp(grid);
|
||||
Console.WriteLine("왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: " + res);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* File: unbounded_knapsack.cs
|
||||
* Created Time: 2023-07-12
|
||||
* Author: hpstory (hpstory1024@163.com)
|
||||
*/
|
||||
|
||||
namespace hello_algo.chapter_dynamic_programming;
|
||||
|
||||
public class unbounded_knapsack {
|
||||
/* 무한 배낭: 동적 계획법 */
|
||||
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];
|
||||
}
|
||||
|
||||
/* 무한 배낭: 공간을 최적화한 동적 계획법 */
|
||||
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];
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Test() {
|
||||
int[] wgt = [1, 2, 3];
|
||||
int[] val = [5, 11, 15];
|
||||
int cap = 4;
|
||||
|
||||
// 동적 계획법
|
||||
int res = UnboundedKnapsackDP(wgt, val, cap);
|
||||
Console.WriteLine("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
|
||||
|
||||
// 공간을 최적화한 동적 계획법
|
||||
res = UnboundedKnapsackDPComp(wgt, val, cap);
|
||||
Console.WriteLine("배낭 용량을 초과하지 않는 물건의 최대 가치: " + res);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user