This commit is contained in:
krahets
2023-09-10 18:37:26 +08:00
parent 4307372a5b
commit e48716c883
6 changed files with 192 additions and 19 deletions

View File

@@ -264,7 +264,24 @@ status: new
=== "C"
```c title="coin_change_greedy.c"
[class]{}-[func]{coinChangeGreedy}
/* 零钱兑换:贪心 */
int coinChangeGreedy(int* coins, int size, int amt) {
// 假设 coins 列表有序
int i = size - 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;
}
```
=== "Zig"