当前位置:网站首页>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];
}
}
边栏推荐
- 一款简洁的文件传输工具
- 尚硅谷MySQL学习笔记
- Flink Yarn Per Job - CliFrontend
- 【MySQL系列】MySQL索引事务
- 深度学习基础-基于Numpy的循环神经网络(RNN)实现和反向传播训练
- 洞见云原生微服务及微服务架构浅析
- Appears in oozie on CDH's hue, error submitting Coordinator My Schedule
- UI自动化测试框架搭建-标记性能较差用例
- Artifact XXXwar exploded Artifact is being deployed, please wait...(已解决)
- 数据机构---第五章树与二叉树---二叉树的概念---应用题
猜你喜欢

Bean的生命周期

Thymeleaf简介

Quartus uses tcl files to quickly configure pins

CDH6的Hue打开出现‘ascii‘ codec can‘t encode characters
[email protected]与YOLO等目标检测模型的非极大值抑制NMS和评价指标(Acc, Precision, Recall, AP, mAP, RoI)、YOLOv5中[email protected]与

带你搞懂MySQL隔离级别,两个事务同时操作同一行数据会怎样?

CDH6 Hue to open a "ASCII" codec can 't encode characters

工件SSMwar exploded 部署工件时出错。请参阅服务器日志了解详细信息
![[C language advanced] file operation (2)](/img/4d/49d9603aeed16f1600d69179477eb3.png)
[C language advanced] file operation (2)

solidity
随机推荐
数据机构---第五章树与二叉树---二叉树的概念---应用题
机器学习文本分类
OpenCV DNN blogFromImage()详解
Quartus uses tcl files to quickly configure pins
DOM 基础操作
在CDH的hue上的oozie出现,提交 Coordinator My Schedule 时出错
【图像融合】基于加权和金字塔实现图像融合附matlab代码
如何进行数据库备份
企业防护墙管理,有什么防火墙管理工具?
contentEditable属性
What can be done to make this SQL into a dangerous SQL?
2022第六届强网杯部分wp
Data Organization --- Chapter 5 Trees and Binary Trees --- The Concept of Binary Trees --- Application Questions
【Leetcode】473. Matchsticks to Square
【ACWing】406. 放置机器人
ICLR 2022 Best Paper: Partial Label Learning Based on Contrastive Disambiguation
Deep Learning Fundamentals - Numpy-based Recurrent Neural Network (RNN) implementation and backpropagation training
获取小猪民宿(短租)数据
[Camp Experience Post] 2022 Cybersecurity Summer Camp
numpy.unique