leetcode -- 322

322. Coin Change

Problem Description

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:

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

Example 2:

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

Note:

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

Solution Method

int coinChange(int* coins, int coinsSize, int amount)
{
    // 和簡單的相比,coins數額不確定,consSize不確定
    int dp[amount+1];
    dp[0] = 0;
    for (int i = 1; i < amount+1;i ++)
    {
        dp[i] = 0x7fffffff;
        for (int j = 0;  j < coinsSize; j ++)
        {
            if (i >= coins[j])
                dp[i] = (dp[i] < dp[i-coins[j]] + 1) ? (dp[i]) : (dp[i-coins[j]] + 1);
        }
    }
    return dp[amount] == 0x7fffffff ? -1: dp[amount];
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章