当前位置:网站首页>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];
}
}
边栏推荐
- Flink Yarn Per Job - Yarn应用
- 20220725 Information update
- Several interview questions about golang concurrency
- 云原生DevOps环境搭建
- 一款简洁的文件传输工具
- recursion: method calls itself
- 尚硅谷MySQL学习笔记
- Leetcode 129求根节点到叶节点数字之和、104二叉树的最大深度、8字符串转换整数(atoi)、82删除排序链表中的重复元素II、204二分查找、94二叉树的中序遍历、144二叉树的前序遍历
- 技术分享 | 接口测试中如何使用Json 来进行数据交互 ?
- LocalDateTime转为Date类型
猜你喜欢
EasyExcel的简单读取操作
C language - branch statement and loop statement
Quartus 使用 tcl 文件快速配置管脚
检查 Oracle 版本的 7 种方法
Spark Sql之join on and和where
Appears in oozie on CDH's hue, error submitting Coordinator My Schedule
ICLR 2022 Best Paper: Partial Label Learning Based on Contrastive Disambiguation
中职网络安全竞赛B7比赛部署流程
Thinkphp 5.0.24变量覆盖漏洞导致RCE分析
在MySQL登录时出现Access denied for user ‘root‘@‘localhost‘ (using password YES) 拒绝访问问题解决
随机推荐
Secondary Vocational Network Security Competition B7 Competition Deployment Process
Spark Sql之union
asyncawait和promise的区别
C language - branch statement and loop statement
【Leetcode】478. Generate Random Point in a Circle(配数学证明)
【ACWing】406. 放置机器人
一个有些意思的项目--文件夹对比工具(一)
Thymeleaf简介
软件测试之移动APP安全测试简析,北京第三方软件检测机构分享
几道关于golang并发的面试题
Work for 5 years, test case design is bad?To look at the big case design summary
oozie startup error on cdh's hue, Cannot allocate containers as requested resource is greater than maximum allowed
使用Ganache、web3.js和remix在私有链上部署并调用合约
cmd command
FAST-LIO2代码解析(二)
mysql8安装make报错如何解决
Use Jenkins for continuous integration, this knowledge point must be mastered
Docker实践经验:Docker 上部署 mysql8 主从复制
字节跳动面试官:请你实现一个大文件上传和断点续传
Leetcode 129求根节点到叶节点数字之和、104二叉树的最大深度、8字符串转换整数(atoi)、82删除排序链表中的重复元素II、204二分查找、94二叉树的中序遍历、144二叉树的前序遍历