problem
給定一組整數陣列coins
,表示不同面額的硬幣,一個整數amount
,請問最少硬幣數,可以組成amount
元,如果不行return -1
solution
至少四種作法
- brute force, backtracking
- backtracking + memo pattern
- dp
- reduce dp
base case
面額0元,不需硬幣數,所以為0。- 遍歷
coins
,不斷尋找是否可以更新更小硬幣數
option 1
1 | class Solution { |
option 2 reduce dp
1 | class Solution { |
analysis
- option 1
- time complexity
O(n^amount)
- space complexity
O(n^2)
- time complexity
- option 2
- time complexity
O(n*amount)
- space complexity
O(n)
- time complexity