leetcode 322零钱兑换
Posted bloglxc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 322零钱兑换相关的知识,希望对你有一定的参考价值。
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 int search(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零钱兑换的主要内容,如果未能解决你的问题,请参考以下文章