ADA 7.3: Coin Changing 找零錢問題
Greedy #2: Coin Changing
Textbook Exercise 16.1
Coin Changing Problem
題目解說
- Input: n dollars and unlimited coins with values
- Output: the minimum number of coins with the total value n
- Cashier’s algorithm: at each iteration, add the coin with the largest value no more than the current total
- 從最大但不超過現在金額的幣值開始給,例如 n = 46
- 店員會找你 4 個 10 元
- 剩下 6 元找給你,1 個 5 元
- 剩下 1 元找給你,1 個 1 元
💡 用這個方法就可以拿到 OPT 嗎? 要怎麼證明呢?
Step 1: Cast Optimization Problem
💡 Coin Changing Problem
Input: n dollars and unlimited coins with values
Output: the minimum number of coins with the total value n
先分析出我們的 Subproblem
- Subproblems
- C(i): 湊出 金額 i 需要的最小的硬幣數量
- 目標: 得到 C(n)
Step 2: Prove Optimal Substructure
如何證明 Optimal Substructure ?
Step 3: Prove Greedy-Choice Property
說明 Greedy-Choice Property 成立
- Greedy choice: 選擇最大的幣值但不超過現在的金額
- 利用矛盾法證明(用 10 ≤ i < 50 例子)
- 我們有個 OPT 可以湊出 i ,greedy choice 要湊出 i 的話一定會拿 10 這個幣值
- 假設沒有任何 OPT 是包含 10 這個幣值的話 → 那麼所有的 OPT 就只能選擇剩下的這幾個 1, 5, 50 來湊成 i
- 首先先把 50 去掉了,因為他超過 i 了
- 如果 OPT 裡面存在 兩個 5 的話,我一定可以把它換成一個 10 變成一個更好的 OPT,所以這裡最多只會存在一個 5
- 如果 OPT 裡面存在 五個 1,我一定可以把它換成一個 5 變成一個更好的 OPT,所以這裡最多只會存在四個 1
- 那麼在這個限制之下我最多只能湊出 9 塊錢 (5 + 4 = 9)
- 這樣就跟一開始的 10 ≤ i < 50 是矛盾的
- 這就說明了我們可以直接把小於 i 但數值最大的硬幣放到 OPT 裡面,就可以帶領我們找到最終的 OPT。