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 };
  • 相关阅读:
    银行卡号每隔4位插入空格
    IE6-8下自定义标签的表现
    Sql Server尝试读取或写入受保护的内存。这通常指示其他内存已损坏
    儿童编程教学scratch 3.0
    Shell 教程入门
    自定义vs2005代码段
    解决Adobe ReaderXI自动关闭问题
    WPF——给button添加背景图片
    WPF 异步加载数据
    Caliburn.Micro中的WindowManager
  • 原文地址:https://www.cnblogs.com/lxc1910/p/10493495.html
Copyright © 2011-2022 走看看