当前位置:网站首页>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];
}
};
边栏推荐
- Leetcode 235. 二叉搜索树的最近公共祖先
- leetcode 20. Valid Parentheses 有效的括号(中等)
- 【Burning】It's time to show your true strength!Understand the technical highlights of the 2022 Huawei Developer Competition in one article
- Chapter 15 HMM模型
- EasyExcel使用
- 迁移学习 & 凯明初始化
- 2022-8-9 第六组 输入输出流
- 【云原生】一文讲透Kubevela addon如何添加腾讯Crane
- Transfer Learning & Kemin Initialization
- The 2022-8-9 sixth group of input and output streams
猜你喜欢
随机推荐
【接口测试】requests 库请求体字符串解码
联盟链技术应用的难点
正则表达式的实际使用
Janus Official DEMO Introduction
68.qt quick-qml多级折叠下拉导航菜单 支持动态添加/卸载 支持qml/widget加载等
leetcode 20. Valid Parentheses 有效的括号(中等)
Redis集群
金仓数据库 KingbaseGIS 使用手册(6.5. 几何对象编辑函数)
都在说云原生,那云原生到底是什么?
完全背包理论
三:OpenCV图片颜色通道数据转换
2020年度SaaS TOP100企业名单
matplotlib散点图自定义坐标轴(文字坐标轴)
浅析量股票化交易的发展现状
一体化伺服电机在三轴钻孔机中的应用
直播预告 | ICML 2022 11位一作学者在线分享神经网络,图学习等前沿研究
【实用工具系列】MathCAD入门安装及快速上手使用教程
【对象——对象及原型链上的属性——对象的操作方法】
【面试高频题】可逐步优化的链表高频题
shell数组









