码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 322零钱兑换

时间:2019-03-08 00:29:25      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:you   动态   NPU   sea   etc   turn   public   search   leetcode   

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零钱兑换

标签:you   动态   NPU   sea   etc   turn   public   search   leetcode   

原文地址:https://www.cnblogs.com/lxc1910/p/10493495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!