File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int coinChange (int [] coins , int amount ) {
3+ /**
4+ 1. understanding
5+ - given coins that can be used, find the minimum count of coins sum up to input amount value.
6+ - [1,2,5]: 11
7+ - 2 * 5 + 1 * 1: 3 -> use high value coin as much as possible if the remain can be sumed up by remain coins.
8+ 2. strategy
9+ - If you search in greedy way, it will takes over O(min(amount/coin) ^ N), given N is the length of coins.
10+ - Let dp[k] is the number of coins which are sum up to amount k, in a given coin set.
11+ - Then, dp[k] = min(dp[k], dp[k-coin] + 1)
12+ 3. complexity
13+ - time: O(CA), where C is the length of coins, A is amount value
14+ - space: O(A), where A is amount value
15+ */
16+ Arrays .sort (coins );
17+
18+ int [] dp = new int [amount + 1 ];
19+ for (int i = 1 ; i <= amount ; i ++) {
20+ dp [i ] = amount + 1 ;
21+ }
22+
23+ for (int coin : coins ) { // O(C)
24+ for (int k = coin ; k <= amount ; k ++) { // O(A)
25+ dp [k ] = Math .min (dp [k ], dp [k -coin ] + 1 );
26+ }
27+ }
28+
29+ return (dp [amount ] >= amount + 1 ) ? -1 : dp [amount ];
30+ }
31+ }
32+
You can’t perform that action at this time.
0 commit comments