leetcode 322零錢兌換
阿新 • • 發佈:2019-03-08
spa com urn 動態規劃 nat ear UNC The different
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
題目大意:
使用幾種硬幣找零錢,每種硬幣可多次使用,求所需硬幣最少數目。若硬幣之和不能等於零錢總數,輸出-1.
解題思路:
用遞歸的動態規劃解決
1 class Solution { 2 public: 3 4 const int inf = 1000000000; 5 vector<vector<int>> v; 6 intsearch(vector<int>& coins, int amount, int idx) { 7 if (amount == 0) 8 return 0; 9 if (idx >= coins.size() || amount < 0) 10 return inf; 11 if (v[idx][amount] >= 0) 12 return v[idx][amount]; 13 int a = search(coins, amount - coins[idx], idx);14 int b = search(coins, amount, idx + 1); 15 v[idx][amount] = min(a + 1, b); 16 return v[idx][amount]; 17 } 18 19 int coinChange(vector<int>& coins, int amount) { 20 v.resize(coins.size(), vector<int>(amount + 1, -1)); 21 int ans = search(coins, amount, 0); 22 if (ans < inf) 23 return ans; 24 return -1; 25 } 26 };
leetcode 322零錢兌換