每日一题 day 58(DP topic)

本文探讨了518.Coin Change 2问题的解决方法。该问题要求计算出组成特定金额的不同硬币组合数量。文章首先介绍了递归方法,并分析了其不足之处;随后提出了一种使用记忆化的动态规划方法,有效地解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

problem

518. Coin Change 2
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

You may assume that you have an infinite number of each kind of coin.

The answer is guaranteed to fit into a signed 32-bit integer.

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

wrong approach

class Solution {
public:
    vector<vector<int>> dp;
    int rec(int amount, int depth, vector<int>& coins){
        if(amount < 0)return 0;
        if(amount == 0){
            // if(dp[depth] == 0)
            //     return dp[depth] = 1;
            // else return 0;
            return 1;
        }
        //if(dp[depth + amount/coins[0]] == 1) return 0;
        
        int res = 0;
        for(auto coin : coins){// iterate through all kinds of coin
            res += rec(amount - coin, depth+1, coins);// tmp = subtree's return
        }
        return res;
    }
    int change(int amount, vector<int>& coins) {
        if(coins.size() == 0) return 0;
        sort(coins.begin(), coins.end());
        dp = vector<int>((amount/coins[0]) + 1, 0);
        return rec(amount, 0, coins);
    }
};

approach memorize dp

class Solution {
public:
    vector<vector<int>> dp;
    int solve(vector<int>& coins,int m,int n){
        if(m==-1 && n>0) 
            return 0;
        if(n==0) 
            return 1;
        if(n<0) 
            return 0;
        if(dp[m][n]!=-1) 
            return dp[m][n];
        return dp[m][n]=solve(coins,m,n-coins[m])+solve(coins,m-1,n);
    }

    int change(int amount, vector<int>& coins) {
        dp = vector<vector<int>>(coins.size(), vector<int>(amount+1, -1));
        return solve(coins,coins.size()-1,amount);
    }
};


在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值