当前位置:网站首页>零钱兑换II——【LeetCode】
零钱兑换II——【LeetCode】
2022-04-23 11:19:00 【D&Blogsphere_.】
class Solution {
//举例amount = 5, coins = [1, 2, 5]
public int change(int amount, int[] coins) {
//递推表达式
int[] dp = new int[amount + 1];
//初始化dp数组,表示金额为0时只有一种情况,也就是什么都不装
dp[0] = 1;
for(int i = 0;i < coins.length; i++) {
//先遍历coins
//dp[j]:凑成总金额j的货币组合数为dp[j]
//第一轮外层for循环,表示考虑coins[0]==1
//凑成总金额1的货币组合数为dp[1] = dp[1] + dp[0]; (就是考虑1和不考虑1的情况之和)此时可能会想dp[1]值是什么,其实dp数组初始化的时候,值全为0了,所以这里dp[1] = dp[1] + dp[0] = 0 + 1 = 1
//当j++,后dp[2] = dp[2] + dp[2-1];(就是考虑2和不考虑2的情况之和)
//为什么这里要初始化j=coins[i]??
//考虑j=coins[1]的情况:此时j==2,则dp[2] = dp[2] + dp[2-2];dp[3] = dp[3] + dp[3-2];
//注意:此时可能会想到dp[3-2]值是多少?是0吗?不是,其实dp数组在上一轮外层for循环的时候就已经对dp数组赋予了新的值了,第二轮外层for循环只是在上一轮的基础之上改变值,dp数组就是个动态变化的数组
for(int j = coins[i]; j <= amount; j++) {
dp[j] += dp[j - coins[i]];
}
// //打印dp数组
// for(int i1 = 0; i1 < dp.length;i1++) {
// System.out.print(dp[i1]);
// }
// System.out.println();
}
return dp[amount];
}
}
版权声明
本文为[D&Blogsphere_.]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_46423830/article/details/124355248
边栏推荐
- vm设置静态虚拟机
- 讯飞2021年营收183亿:同比增41% 净利为15.56亿
- 微型机器人的认知和研发技术
- laravel-admin表单验证
- Cygwin 中的 rename 用法
- mysql创建存储过程及函数详解
- Get things technology network optimization - CDN resource request Optimization Practice
- Learning go language 0x08: practice using error in go language journey
- MySQL partition table can be classified by month
- An interesting interview question
猜你喜欢
随机推荐
GPU, CUDA,cuDNN三者的关系总结
数据库管理软件SQLPro for SQLite for Mac 2022.30
map<QString, bool> 的使用记录
学习 Go 语言 0x03:理解变量之间的依赖以及初始化顺序
mysql中整数数据类型tinyint详解
解决 『SunCertPathBuilderException:unable to find valid certification path to requested target』 问题
Learning website materials
C#的学习笔记【八】SQL【一】
PDMS软光刻加工过程
Solve the problem of "suncertpathbuilderexception: unable to find valid certification path to requested target"
Upgrade the functions available for cpolar intranet penetration
Three web components (servlet, filter, listener)
Go interface usage
MySQL sorting feature details
Usage Summary of datetime and timestamp in MySQL
学习 Go 语言 0x02:对切片 Slice 的理解
SVN的使用:
Mysql排序的特性详情
Learning go language 0x08: practice using error in go language journey
Detailed explanation of writing sequence and execution sequence of MySQL series SQL query statements