当前位置:网站首页>LeetCode_279_完全平方数
LeetCode_279_完全平方数
2022-08-01 23:54:00 【Fitz1318】
题目链接
题目描述
给你一个整数 n ,返回 和为 n 的完全平方数的最少数量 。
完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是。
示例 1:
输入:n = 12
输出:3
解释:12 = 4 + 4 + 4
示例 2:
输入:n = 13
输出:2
解释:13 = 4 + 9
提示:
1 <= n <= 10^4
解题思路
动态递归四部曲
- 确定
dp数组以及下标的含义dp[j]:和为j的完全平方数的最少数量
- 确定递推公式
dp[j] = Math.min(dp[j], dp[j - i * i] + 1)
dp数组初始化dp[0] = 0- 非
0下标的dp[j]一定要初始为最大值,这样dp[j]在递推的时候才不会被初始值覆盖
- 确定遍历顺序
- 如果求组合数就是外层for循环遍历物品,内层for遍历背包
- 如果求排列数就是外层for循环遍历背包,内层for循环遍历物品
- 举例推导
dp数组
AC代码
class Solution {
public int numSquares(int n) {
int[] dp = new int[n + 1];
int max = n + 1;
Arrays.fill(dp, max);
dp[0] = 0;
for (int i = 1; i * i <= n; i++) {
for (int j = i * i; j <= n; j++) {
if (dp[j - i * i] != max) {
dp[j] = Math.min(dp[j], dp[j - i * i] + 1);
}
}
}
return dp[n];
}
}
边栏推荐
猜你喜欢

Excel表格数据导入MySQL数据库

Get piggy homestay (short-term rental) data

Wincc报表教程(SQL数据库的建立,wincc在数据库中保存和查询数据,调用Excel模板把数据保存到指定的位置和打印功能)

经典文献阅读之--DLO

UI自动化测试框架搭建-标记性能较差用例

Bean的生命周期

Secondary Vocational Network Security Competition B7 Competition Deployment Process
![[C language advanced] file operation (2)](/img/4d/49d9603aeed16f1600d69179477eb3.png)
[C language advanced] file operation (2)

OpenCV DNN blogFromImage()详解

Classical Literature Reading--DLO
随机推荐
辛普森悖论
Convert LocalDateTime to Date type
What can be done to make this SQL into a dangerous SQL?
Special characters & escapes in bat
机器学习文本分类
ELK日志采集
Flink Yarn Per Job - CliFrontend
Use Jenkins for continuous integration, this knowledge point must be mastered
使用Jenkins做持续集成,这个知识点必须要掌握
UI自动化测试框架搭建-标记性能较差用例
DOM 事件及事件委托
Appears in oozie on CDH's hue, error submitting Coordinator My Schedule
solidity
【Leetcode】479. Largest Palindrome Product
cdh的hue上oozie启动报错,Cannot allocate containers as requested resource is greater than maximum allowed
Excel文件读写(创建与解析)
如何用Redis实现分布式锁?
cdh6打开oozieWeb页面,Oozie web console is disabled.
Quartus 使用 tcl 文件快速配置管脚
numpy.hstack