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 };
  • 相关阅读:
    RADAR毫米波雷达传感器
    固态LiDAR,半固态混合LiDAR,机械LiDAR
    Lidar激光雷达市场
    echarts 环形图中自定义文字
    uni-app base64 无法显示问题
    实战二(上):针对非业务的通用框架开发,如何做需求分析和设计?
    实战一(下):如何实现一个遵从设计原则的积分兑换系统?
    实战一(上):针对业务系统的开发,如何做需求分析和设计?
    学而不记,不学无异 -- English learning
    springmvc 传入返回参数更改
  • 原文地址:https://www.cnblogs.com/lxc1910/p/10493495.html
Copyright © 2011-2022 走看看