当前位置:网站首页>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];
}
};
边栏推荐
猜你喜欢
随机推荐
Janus Official DEMO Introduction
干货!迈向鲁棒的测试时间适应
测试2年,当时身边一起入行的朋友已经月薪20k了,自己还没过万,到底差在了哪里?
三:OpenCV图片颜色通道数据转换
全球不用交税的国家,为什么不交
都在说云原生,那云原生到底是什么?
【AtomicInteger】常规用法
EasyExcel使用
【JZOF】77按之字形打印二叉树
[Interface Test] Decoding the request body string of the requests library
集群的基础形式
【JZOF】32从上往下打印二叉树
1018.值周
tiup cluster upgrade
力扣:518. 零钱兑换 II
&& 不是此版本的有效语句分隔符
五分钟商学院(基础---商业篇)
HUAWEI CLOUD escorts the whole process of "Wandering Ark" for the first time, creating a popular brand
PyQt5: Getting Started Tutorial
What are the basic steps to develop a quantitative trading strategy?