当前位置:网站首页>Force buckle: 279. Perfect square
Force buckle: 279. Perfect square
2022-08-10 00:33:00 【empty__barrel】
题目:
给你一个整数 n ,返回 和为 n 的完全平方数的最少数量 .
完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积.例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是.
dp数组含义:
dp[j]:和为j的完全平方数的最少数量为dp[j]
递归公式:
dp[j] = min(dp[j - i * i] + 1, dp[j]);
初始化:
- dp[0]=0完全是为了递推公式,Because the number given in the question itself is a perfect square,那么此时dp即dp[j - i * i] + 1,At this point the value should be 1,同时j-i*i=0,所以dp[0]应该=0;
- 从递归公式dp[j] = min(dp[j - i * i] + 1, dp[j]);中可以看出每次dp[j]都要选最小的,所以非0w下标的dp[j]一定要初始为最大值,这样dp[j]在递推的时候才不会被初始值覆盖
遍历顺序:
Just a complete knapsack question,同时dpno sequence,所以对forNesting of loops is not required.
This topic does not clearly state which integers are put into the knapsack,You need to identify for yourself.These values should be from1到sqrt(n)的.
代码:
// 版本一
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n + 1, INT_MAX);
dp[0] = 0;
for (int i = 1; i <= n; i++) {
// 遍历背包
for (int j = 1; j * j <= i; j++) {
// 遍历物品
dp[i] = min(dp[i - j * j] + 1, dp[i]);
}
}
return dp[n];
}
};
代码:
// 版本二
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n + 1, INT_MAX);
dp[0] = 0;
for (int i = 1; i * i <= n; i++) {
// 遍历物品
for (int j = 1; j <= n; j++) {
// 遍历背包
if (j - i * i >= 0) {
dp[j] = min(dp[j - i * i] + 1, dp[j]);
}
}
}
return dp[n];
}
};
边栏推荐
- 金仓数据库 KingbaseGIS 使用手册(6.4. 几何对象存取函数)
- 上海一科技公司刷单被罚22万,揭露网络刷单灰色产业链
- 68.qt quick-qml多级折叠下拉导航菜单 支持动态添加/卸载 支持qml/widget加载等
- Interfering with BGP routing---community attributes
- 三:OpenCV图片颜色通道数据转换
- “我“是一名测试/开发程序员,小孙的内心独白......
- 70. 爬楼梯进阶版
- 2021年国内外五大BI厂商——优秀的商业智能工具推荐
- 测试2年,当时身边一起入行的朋友已经月薪20k了,自己还没过万,到底差在了哪里?
- 生成NC文件时,报错“未定义机床”
猜你喜欢
探索TiDB Lightning源码来解决发现的bug
HBuilder X 不能运行到内置终端
安踏携手华为运动健康共同验证冠军跑鞋 创新引领中国体育
HUAWEI CLOUD escorts the whole process of "Wandering Ark" for the first time, creating a popular brand
生成NC文件时,报错“未定义机床”
少儿编程 电子学会图形化编程等级考试Scratch三级真题解析(判断题)2022年6月
iNFTnews | 迪士尼如何布局Web3
【TS技术课堂】时间序列预测
继承关系下构造方法的访问特点
毕昇编译器优化:Lazy Code Motion
随机推荐
如何正则匹配乱码?
函数习题(下)
LiveData : Transformations.map和 Transformations.switchMap用法
mysql中的key是怎么用的,或者这个值有什么意义,如下图?
Janus官方DEMO介绍
Analyses the development status quo of stock trading
【燃】是时候展现真正的实力了!一文看懂2022华为开发者大赛技术亮点
VR全景拍摄如何拍摄?如何使用拍摄器材?
Comprehensive analysis of FPGA basics
五分钟商学院(基础---商业篇)
[WeChat applet development (8)] Summary of audio background music playback problems
Miscellaneous talk - the sorrow of programmers
34. Fabric2.2 证书目录里各文件作用
继承关系下构造方法的访问特点
多线程是同时执行多个线程的吗
SRv6性能测量
tiup cluster template
Interfering with BGP routing---community attributes
The 2022-8-9 sixth group of input and output streams
CV复习:softmax代码实现