zoukankan      html  css  js  c++  java
  • 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 };

     方法二:迭代

    定义一个大小为amount + 1的数组dp,dp[i]代表当总钱币数为i时可兑换的最少的钱币个数,

    当i为0时只需要0个钱币,因此dp[0]等于0。

    当求dp[k]时,先令dp[k]等于正无穷,然后遍历所有钱币,若钱币j币值coins[j]小于k,令dp[k] = min(dp[k - coins[j] ] + 1, dp[k])。

     1 class Solution {
     2 public:
     3     const int inf = 1000000000;
     4     vector<int> dp;
     5     int coinChange(vector<int>& coins, int amount) {
     6         int N = coins.size();
     7         dp.resize(amount + 1);
     8         dp[0] = 0;
     9         for (int i = 1; i <= amount; i++) {
    10             dp[i] = inf;
    11             for (int j = 0; j < N; j++) {
    12                 if (coins[j] <= i)
    13                     dp[i] = min(dp[i], dp[i - coins[j]] + 1);
    14             }
    15         }
    16         if (dp[amount] == inf)
    17             return -1;
    18         return dp[amount];
    19     }
    20 };
  • 相关阅读:
    多个自定义覆盖物注册点击事件,点击某个覆盖物后获得它的坐标
    C# 文件操作(全部) 追加、拷贝、删除、移动文件、创建目录 修改文件名、文件夹名
    如何添加EXEStealth 2.5x 壳
    PACS系统简易
    好用的后端模版
    E信通项目总结[转]
    平台型产品的设计思路[转]
    baidu思维脑图在线编辑器
    Web 前端攻防(2014版)-baidu ux前端研发部
    访谈标叔:给新人设计师的建议【转】
  • 原文地址:https://www.cnblogs.com/lxc1910/p/10493495.html
Copyright © 2011-2022 走看看