Files
hello-algo/ko/codes/dart/chapter_dynamic_programming/coin_change.dart
Yudong Jin 2f561d3d51 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
2026-10-29 03:46:43 +08:00

69 lines
2.0 KiB
Dart

/**
* File: coin_change.dart
* Created Time: 2023-08-11
* Author: liuyuxin (gvenusleo@gmail.com)
*/
import 'dart:math';
/* 동전 교환: 동적 계획법 */
int coinChangeDP(List<int> coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// dp 테이블을 초기화한다
List<List<int>> dp = List.generate(n + 1, (index) => List.filled(amt + 1, 0));
// 상태 전이: 첫 번째 행과 첫 번째 열
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] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
return dp[n][amt] != MAX ? dp[n][amt] : -1;
}
/* 동전 교환: 공간을 최적화한 동적 계획법 */
int coinChangeDPComp(List<int> coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// dp 테이블을 초기화한다
List<int> dp = List.filled(amt + 1, 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] = min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] != MAX ? dp[amt] : -1;
}
/* 실행 코드 */
void main() {
List<int> coins = [1, 2, 5];
int amt = 4;
// 동적 계획법
int res = coinChangeDP(coins, amt);
print("목표 금액을 만드는 데 필요한 최소 동전 개수 = $res");
// 공간을 최적화한 동적 계획법
res = coinChangeDPComp(coins, amt);
print("목표 금액을 만드는 데 필요한 최소 동전 개수 = $res");
}