hello-algo/codes/swift/chapter_greedy/coin_change_greedy.swift

55 lines
1.7 KiB
Swift
Raw Normal View History

/**
* File: coin_change_greedy.swift
* Created Time: 2023-09-03
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
func coinChangeGreedy(coins: [Int], amt: Int) -> Int {
// coins
var i = coins.count - 1
var count = 0
var amt = amt
//
while amt > 0 {
//
while i > 0 && coins[i] > amt {
i -= 1
}
// coins[i]
amt -= coins[i]
count += 1
}
// -1
return amt == 0 ? count : -1
}
@main
enum CoinChangeGreedy {
/* Driver Code */
static func main() {
//
var coins = [1, 5, 10, 20, 50, 100]
var amt = 186
var res = coinChangeGreedy(coins: coins, amt: amt)
print("\ncoins = \(coins), amount = \(amt)")
print("凑到 \(amt) 所需的最少硬币数量为 \(res)")
//
coins = [1, 20, 50]
amt = 60
res = coinChangeGreedy(coins: coins, amt: amt)
print("\ncoins = \(coins), amount = \(amt)")
print("凑到 \(amt) 所需的最少硬币数量为 \(res)")
print("实际上需要的最少数量为 3 ,即 20 + 20 + 20")
//
coins = [1, 49, 50]
amt = 98
res = coinChangeGreedy(coins: coins, amt: amt)
print("\ncoins = \(coins), amount = \(amt)")
print("凑到 \(amt) 所需的最少硬币数量为 \(res)")
print("实际上需要的最少数量为 2 ,即 49 + 49")
}
}