<pre name="code" class="java">/**
* given an array 'c[]' represents coins and a target value 'amount'
* suppose the solution for 'amount' is sol(a) which refers to minimum # of conins to reach the amount
* easy to know sol(a) = min{sol(a-c[1])+1, sol(a-c[2]+1, ..., sol(a-c[n])+1)}
* for example, c[] = {1, 2, 3} a = 4
* sol(4) = min{sol(3)+1, sol(2)+1, sol(1)+1}
* sol(1) = min{sol(0)+1} = 1 sol(3) = min{sol(2)+1, sol(1)+1, sol(0)+1} = 1 sol(2) = 1
* therefore, sol(4) = 2
*/
public class Solution {
public int coinChange(int[] coins, int amount) {
int[] sol = new int[amount+1];
for (int i=1; i<=amount; i++) {
int min = Integer.MAX_VALUE;
for (int c : coins)
if (i >= c)
if (sol[i-c] < min) min = sol[i-c]+1;
sol[i] = min;
}
return sol[amount] == Integer.MAX_VALUE ? -1 : sol[amount];
}
}
Leetcode 322. Coin Change
最新推荐文章于 2022-07-01 12:30:23 发布