150強訪談中等

硬幣找零

「硬幣找零」問題的詳細指南和 Python 實作。

問題陳述

中等

給你一個代表不同面額硬幣的整數數組硬幣和代表總金額的整數金額。

返回彌補該金額所需的最少數量的硬幣。如果該金額不能由任何硬幣組合組成,則傳回 -1。

您可能會假設您擁有無限數量的每種硬幣。

寫一個函數 coinChange(coins: List[int], amount: int) -> int

約束條件
  • 1 <= len(coins) <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4

範例

Example 1
Input
coins = [1,2,5], amount = 11
Output
3
Explanation

11 = 5 + 5 + 1

Example 2
Input
coins = [2], amount = 3
Output
-1
Explanation

3 cannot be formed using only coins of denomination 2.

Example 3
Input
coins = [1], amount = 0
Output
0
Explanation

No coins are needed to make amount 0.

Need a Hint?
考慮使用一維 DP 特定的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。