mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-28 04:20:44 +08:00
build
This commit is contained in:
@@ -16,7 +16,7 @@ status: new
|
||||
|
||||
!!! question
|
||||
|
||||
给定 $n$ 种硬币,第 $i$ 个硬币的面值为 $coins[i - 1]$ ,目标金额为 $amt$ ,每种硬币可以重复选取,问能够凑出目标金额的最少硬币个数。如果无法凑出目标金额则返回 $-1$ 。
|
||||
给定 $n$ 种硬币,第 $i$ 种硬币的面值为 $coins[i - 1]$ ,目标金额为 $amt$ ,每种硬币可以重复选取,问能够凑出目标金额的最少硬币个数。如果无法凑出目标金额则返回 $-1$ 。
|
||||
|
||||
这道题的贪心策略在生活中很常见:给定目标金额,**我们贪心地选择不大于且最接近它的硬币**,不断循环该步骤,直至凑出目标金额为止。
|
||||
|
||||
@@ -174,7 +174,24 @@ status: new
|
||||
=== "Dart"
|
||||
|
||||
```dart title="coin_change_greedy.dart"
|
||||
[class]{}-[func]{coinChangeGreedy}
|
||||
/* 零钱兑换:贪心 */
|
||||
int coinChangeGreedy(List<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;
|
||||
}
|
||||
```
|
||||
|
||||
=== "Rust"
|
||||
|
||||
Reference in New Issue
Block a user