322 Coin Change

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:

Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Input: coins = [2], amount = 3
Output: -1

Note:

You may assume that you have an infinite number of each kind of coin.

解釋下題目:

1. 動態規劃

實際耗時:xxms

public int coinChange(int[] coins, int amount) {
    if (amount < 1) {
        return 0;
    }
    int[] dp = new int[amount];
    return helper(coins, amount, dp);
    //System.out.println(Arrays.toString(dp));
}

private int helper(int[] coins, int left, int[] dp) {
    if (left < 0) {
        return -1;
    }
    if (left == 0) {
        //found the answer
        return 0;
    }
    if (dp[left - 1] != 0) {
        return dp[left - 1];
    }
    int min = Integer.MAX_VALUE;
    for (int coin : coins) {
        int tmp = helper(coins, left - coin, dp);
        if (tmp >= 0) {
            if (tmp < min) {
                min = tmp + 1;
            }
        }
    }
    dp[left - 1] = (min == Integer.MAX_VALUE ? -1 : min);
    return dp[left - 1];
}
踩過的坑:[186,419,83,408],6249 這組。

??首先確定這題絕對不是貪心。然后其實如果你知道amount = 500怎么求的話,其實500以下的所有數字你也知道怎么求了。然后算法有個出口,我之前搓一直錯在這里,就是如果dp[left - 1] != 0,這里我之前寫的是大于,其實如果是-1也算找到了答案,所以要改成不等于0,其他的應該就沒難度了。

時間復雜度O(n*amount) n為coins這個數組的長度
空間復雜度O(amount)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,424評論 0 10
  • 參考 [LeetCode] Coin Change 硬幣找零 題目描述:You are given coins o...
    小碧小琳閱讀 1,194評論 0 1
  • 問題描述 You are given coins of different denominations and a...
    JERORO_閱讀 168評論 0 0
  • 題目鏈接 tag: Medium; Dynamic Programming; question:??You are...
    xingzai閱讀 97評論 0 0
  • 問題描述 You are given coins of different denominations and a...
    codingXue閱讀 346評論 0 0