当前位置:网站首页>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];
}
};
边栏推荐
- 使用股票量化交易接口需要具备怎么样的心态
- 三:OpenCV图片颜色通道数据转换
- Mysql/stonedb - slow SQL - 2022-08-09 Q16 analysis
- Bi Sheng Compiler Optimization: Lazy Code Motion
- 金仓数据库 KingbaseGIS 使用手册(6.6. 几何对象校验函数、6.7. 空间参考系函数)
- 深圳堡垒机厂家有哪些?重点推荐哪家?
- CV复习:softmax代码实现
- Forbidden (CSRF token missing or incorrect.): /
- HUAWEI CLOUD escorts the whole process of "Wandering Ark" for the first time, creating a popular brand
- 2022-8-9 第六组 输入输出流
猜你喜欢
随机推荐
【JZOF】77按之字形打印二叉树
五分钟商学院(基础---商业篇)
Snap: 322. Change of Change
上海一科技公司刷单被罚22万,揭露网络刷单灰色产业链
tiup cluster template
Install win7 virtual machine in Vmware and related simple knowledge
如何知道电脑开机记录?
HUAWEI CLOUD escorts the whole process of "Wandering Ark" for the first time, creating a popular brand
torch.distributed多卡/多GPU/分布式DPP(二)——torch.distributed.all_reduce(reduce_mean)&barrier&控制进程执行顺序&随机数种子
Interfering with BGP routing---community attributes
【TS技术课堂】时间序列预测
守护进程
tiup cluster scale-out
tiup cluster start
Bi Sheng Compiler Optimization: Lazy Code Motion
How to insist to use procedural system?
用户要清晰知道,量化交易并非简单的程序
matplotlib散点图颜色分组图例
新增一地公布2022下半年软考报考时间
多线程是同时执行多个线程的吗