This commit is contained in:
krahets
2023-07-22 03:58:19 +08:00
parent 5f2154b49d
commit 79ade24902
5 changed files with 98 additions and 5 deletions
+18 -1
View File
@@ -119,7 +119,24 @@ status: new
=== "C#"
```csharp title="coin_change_greedy.cs"
[class]{coin_change_greedy}-[func]{coinChangeGreedy}
/* 零钱兑换:贪心 */
int coinChangeGreedy(int[] coins, int amt) {
// 假设 coins 列表有序
int i = coins.Length - 1;
int count = 0;
// 循环进行贪心选择,直到无剩余金额
while (amt > 0) {
// 找到小于且最接近剩余金额的硬币
while (coins[i] > amt) {
i--;
}
// 选择 coins[i]
amt -= coins[i];
count++;
}
// 若未找到可行方案,则返回 -1
return amt == 0 ? count : -1;
}
```
=== "Swift"