动态规划解决最少硬币凑成m元钱

322. Coin Change

 
Question Editorial Solution
  My Submissions
  • Total Accepted: 30668
  • Total Submissions: 120210
  • Difficulty: Medium

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)

Example 2:
coins = [2], amount = 3

return -1.


public class Solution
{
    /*长度为m的数组c[1...m]中存放一系列子结果,即c[i]为要凑的钱数为i时所需的最少硬币数,则c[m]为所求
  当要找的钱数i(1a[j])
                {
                    if(c[i]==0&&c[i-a[j]]!=0)
                    {
                        c[i]=c[i-a[j]]+1;
                        System.out.println("c"+i+":"+c[i]);
                    } 
                    else
                    {
                        if(c[i-a[j]]!=0)
                        {
                            c[i]=c[i-a[j]]+1

另一种更有效的方法
public int coinChange(int[] coins, int amount) {
    if (amount < 1) return 0;
    int[] dp = new int[amount + 1]; 
    Arrays.fill(dp, Integer.MAX_VALUE);
    dp[0] = 0;
    for (int coin : coins) {
        for (int i = coin; i <= amount; i++) {
            if (dp[i - coin] != Integer.MAX_VALUE) {
                dp[i] = Math.min(dp[i], dp[i - coin] + 1);
            }
        }
    }
    return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
}


你可能感兴趣的:(算法)