当前位置:网站首页>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];
}
};
边栏推荐
猜你喜欢

【TS技术课堂】时间序列预测

iNFTnews | 迪士尼如何布局Web3

Install win7 virtual machine in Vmware and related simple knowledge

Bi Sheng Compiler Optimization: Lazy Code Motion

金仓数据库 KingbaseGIS 使用手册(6.4. 几何对象存取函数)

ElasticSearcch集群

matplotlib散点图自定义坐标轴(文字坐标轴)

Redis集群

2020年度SaaS TOP100企业名单

2022-08-09 mysql/stonedb-subquery performance improvement-introduction
随机推荐
tiup cluster start
linux上使用docker安装redis
Leetcode 98. 验证二叉搜索树
使用股票量化交易接口需要具备怎么样的心态
伦敦银行情中短线的支撑和阻力位
68.qt quick-qml多级折叠下拉导航菜单 支持动态添加/卸载 支持qml/widget加载等
Controller层代码这么写,简洁又优雅!
Analyses the development status quo of stock trading
Mysql集群 ShardingSphere
SRv6性能测量
&& 不是此版本的有效语句分隔符
制定量化交易策略的基本步骤有哪些?
Basic operations of xlrd and xlsxwriter
深度学习100例 —— 循环神经网络(RNN)实现股票预测
浅析量股票化交易的发展现状
YGG 经理人杯总决赛已圆满结束,来看看这份文字版总结!
torch.distributed多卡/多GPU/分布式DPP(二)——torch.distributed.all_reduce(reduce_mean)&barrier&控制进程执行顺序&随机数种子
iNFTnews | 迪士尼如何布局Web3
Transfer Learning & Kemin Initialization
高手这样看现货白银走势图