This commit is contained in:
krahets
2023-08-13 19:36:03 +08:00
parent 059a849167
commit 971624c291
31 changed files with 1750 additions and 156 deletions

View File

@@ -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"