mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-26 11:32:31 +08:00
build
This commit is contained in:
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user