LeetCodde[322] Coin Change

来源:互联网 发布:手机可以做淘宝网店吗 编辑:程序博客网 时间:2024/05/01 00:24

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.

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

动态规划,初始值除了 result[0] 都设置为不可能达到的大数(这里设为amount + 1),因为此题求的是最小值

每一个 result[i] 都遍历一下 coins ,找到能达到的最小值,最后 result[amount] 如果还是 amount + 1 就说明找不开,否则 result[amount] 就是可以达到的最小值

class Solution {public:int coinChange(vector<int>& coins, int amount) {if (coins.empty() || amount < 0)return -1;int len = coins.size();int* result = new int[amount + 1];result[0] = 0;for (int i = 1; i <= amount; i++){result[i] = amount + 1;for (int j = 0; j < len; j++){if (i >= coins[j]){result[i] = (result[i - coins[j]] + 1) < result[i] ? result[i - coins[j]] + 1 : result[i];}}}if (result[amount] < amount + 1)return result[amount];elsereturn -1;}};





0 0
原创粉丝点击