You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/zh-hant/codes/swift/chapter_greedy/coin_change_greedy.swift

55 lines
1.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 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")
}
}