Coin Changing Problem(01背包)

Coin Changing Problem(01背包)


题目
Find the minimum number of coins to make change for n cents using coins of denominations d1, d2,…, dm.
The coins can be used any number of times.

输入
Two integers n and m are given in the first line.
The available denominations are given in the second line.

输出
Print the minimum number of coins in a line.

数据范围

1 ≤ n ≤ 50000

1 ≤ m ≤ 20

1 ≤ denomination ≤ 10000

The denominations are all different and contain 1.(各面值均不同,其中必须包含1)

样例输入1

55 4
1 5 10 50

样例输出1

2

样例输入2

15 6
1 2 7 8 12 50

样例输出2

2

样例输入3

65 6
1 2 7 8 12 50

样例输出3

3

题意
现有面值为C1,C2,…,Cm元的m种硬币,求支付n元时所需的最少硬币数。
各面值的硬币量不限使用。

思路
最近开始上手动态规划。

首先我们设定两个数组c与t:

int c[25];       //c[i]:第i个硬币的面值 
int t[50050];    //t[j]:当支付数为j元时所需的硬币最少量

当支付额为 j 元时,t[j] 为不放 c[i] 总额达到 j 元的最少数量,t[j-c[i]]+1为取1枚c[i]总额达到 j 元的最少数量。

t[j]的值应为两者之间较小值。

此时我们就得到了这道题的状态转移方程:

t[j]=min(t[j],t[j-c[i]]+1); 

然后补充一下代码就可以了。

「伊丽莎白」!
在这里插入图片描述
代码

#include<bits/stdc++.h>
using namespace std;
int c[25];       //c[i]:第i个硬币的面值 
int t[50050];    //t[j]:当支付数为j元时所需的硬币最少量
int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        for(int i=1;i<=m;i++)
            cin>>c[i];
        for(int i=1;i<=n;i++)
            t[i]=1e9+7;       //求最小值设置比较大的值,如果是求最大值就设小一点
        t[0]=0;               
        for(int i=1;i<=m;i++)
            for(int j=0;j+c[i]<=n;j++)
            t[j+c[i]]=min(t[j+c[i]],t[j]+1);  //状态转移方程
        cout<<t[n]<<endl;
    }
}

自己对于动态规划的理解还没有很深入,对于一些细节也不是很理解。
一些细节方面应该还会再改动。

我()懂()你()没()懂()。
在这里插入图片描述

针不戳~

下次再见!
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值