当前位置:网站首页>【无标题】
【无标题】
2022-07-16 14:43:00 【小迅想变强】
链接:https://leetcode.cn/problems/coin-change/solution/chun-c-by-xun-ge-v-4nmv/
来源:力扣(LeetCode)
题目

示例

思路
解题思路
1、确定状态
简单的说,就是解动态规划时需要开一个数组,数组的每个元素f[i]或者f[i][j]代表什么,类似解数学题中,xyz代表什么一样,具体分为下面两个步骤:
-------研究最优策略的最后一步
-------化为子问题
2、转移方程
根据子问题定义直接得到
3、初始条件和边界情况
初始条件一般都是a[0]、a[1]这种,多看看
边界条件主要是看数组的边界,数组越不越界
4、计算顺序
利用之前的计算结果
使用动态规划思路
我们定义一个dp数组,大小 amount+1 ,dp[i]表示整数金额 i 需要dp[i]个银币
所以dp[i] = dp[i - coins[j]] + 1 -> 表示当前金额 i 需要 i - coins[j]需要的银币加 1
所以遍历整个coins 更新dp[i] 寻找最小的银币数
在dp初始化时,我们将其附最大值,如果 dp[i - coins[j]] == 最大值,表示当前金额 i - coins[j] ,在coins中不存在 也保存最大值
代码
int cmp(const void * a, const void * b)
{
return *(int *)a - *(int *)b;
}
#define MIN(a , b) ((a) < (b) ? (a) : (b))
int coinChange(int* coins, int coinsSize, int amount){
qsort(coins, coinsSize, sizeof(coins[0]), cmp);//升序
int dp[amount + 1];
dp[0] = 0;
for(int i = 1; i <= amount; i++)//遍历dp数组
{
dp[i] = amount + 1;//初始化最大值
for(int j = 0; j < coinsSize; j++)//动态更新dp[i]
{
if(coins[j] > i)
{
break;
}
else
{
dp[i] = MIN(dp[i] , dp[i - coins[j]] + 1);
}
}
}
return dp[amount] == (amount+1) ? -1 : dp[amount];
}
时间空间复杂度

边栏推荐
- 02-回顾多线程
- Excel finds characters from the right and intercepts them
- 【C语言刷LeetCode】134. 加油站(M)
- Three kinds of "squeeze dry" enterprise equipment clothing ERP budget
- Leetcode 49. 字母异位词分组
- 学习路之PHP--post获取不到请求数据
- [Luogu p6891] ビルのりけ 4 (DP) (conclusion)
- uCOS-III学习笔记——软件定时器
- 复盘:BN和Dropout共同使用时会出现的问题
- 不知道如何提高视觉语言大模型?浙大与联汇研究院提出新型多维度评测框架...
猜你喜欢

MySQL 变量、流程控制与游标

A game research and development company in Shenzhen installed monitoring for each station. Netizen: it's comparable to imprisonment!

自定义类型——结构体

复盘:池化层(Pooling)的反向传播过程,平均池化,最大值池化都是如何反向传播的
![Translation and interpretation of the paper: learning logic rules for reasoning on knowledge graphs [rnnlogic]](/img/71/5a80849f780414cd29135a25525281.png)
Translation and interpretation of the paper: learning logic rules for reasoning on knowledge graphs [rnnlogic]
![[graduation project] network public opinion hotspot analysis system based on Emotional Analysis](/img/b6/c297f9b81446d8b2d0220c5f8774b5.png)
[graduation project] network public opinion hotspot analysis system based on Emotional Analysis

Huawei equipment configuration RF tuning

ssd训练自己的数据集

给即将毕业要走往程序员道路的10条建议(精彩配图)

MySQL MySQL8其它新特性
随机推荐
[Luogu p6891] ビルのりけ 4 (DP) (conclusion)
软件测试面试题:软件质量保证体系是什么 国家标准中与质量保证管理相关的几个标准是什么?他们的编号和全称是什么?
【Ucos-III源码分析】——互斥信号量(互斥锁)
软件测试面试题:软件产品质量特性是什么?
Your first orthodontic condition (continuously updating)
云原生(三十五) | Prometheus入门和安装
自定义类型——结构体
Flask response
Bean的生命周期详解
Error :Could not decode ...With “UTF-8“-encoding. Editing not possible
WordPress personal blog theme wp-reason-v1.0
02-回顾多线程
2022 latest Tianjin Construction Safety Officer simulation question bank and answers
Arthas的常见用法
TCP拥塞控制详解 | 6. 主动队列管理
Flask-响应
【Ucos-III源码分析】——时间片轮转
MySQL 变量、流程控制与游标练习
【Ucos-III源码分析】——内存管理机制
《遥远的救世主》遵守客观规律(七)——文化属性