zoukankan      html  css  js  c++  java
  • Leetcode 518 Coin Change 2

    ###给定硬币面额和种类,给定总金额,问有多少种组合方法; https://leetcode-cn.com/problems/coin-change-2/

    Example 1: Input: amount = 5, coins = [1, 2, 5] Output: 4 Explanation: there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1

    Example 2: Input: amount = 3, coins = [2] Output: 0 Explanation: the amount of 3 cannot be made up just with coins of 2. Example 3: Input: amount = 10, coins = [10] Output: 1   Note: You can assume that 0 ⇐ amount ⇐ 5000 1 ⇐ coin ⇐ 5000 the number of coins is less than 500 the answer is guaranteed to fit into signed 32-bit integer

      硬币金额=重量,背包=金额,dp记录组合数

    这题注意点就是说,一般要存满背包(这里的是金额),我们一般要用MAX去初始化数组,但是这题不是  

    * 这里用0初始化可以直接当做0种方法

    ####* 然后注意对于金额0,应该是有1种方法(就是什么都不装)(这里就能够让面额2硬币,对于金额2来说有d[2] = d[2]+d[2-2] = 1) ####* 可以重复使用,内层递增循环 ####* 另外注意更新的时候 状态转移方程应该是d[v] = d[v] + d[v-coins[i]],d[v]是上一行的结果,d[v-coins[i]]是这一行左边的结果   如图  

    class Solution {
    public:
        int change(int amount, vector<int>& coins) {
            int dp[amount+1];
            fill(dp,dp+amount+1,0);
            dp[0] = 1;
            int n = coins.size();
            for(int i=0;i<n;i++){
                for(int j=coins[i];j<=amount;j++){
                    dp[j] = dp[j]+dp[j-coins[i]];
                }
            }
            return dp[amount];
        }
    };
    












    种一棵树最好的时间是十年前,其次是现在。
  • 相关阅读:
    江の島西浦写真館1-1
    花咲舞が黙っていない2-5
    花咲舞が黙っていない2-4
    花咲舞が黙っていない2-3
    花咲舞が黙っていない2-2
    花咲舞が黙っていない2-1
    花咲舞がだまってない1-5
    花咲舞がだまってない1-4
    花咲舞がだまってない1-3
    花咲舞が黙っていない1-2
  • 原文地址:https://www.cnblogs.com/islch/p/12599228.html
Copyright © 2011-2022 走看看