当前位置:网站首页>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启动失败问题Job for mysqld.service failed because the control process exited with error code
- The Spark of Sql join on the and and where
- 数据机构---第五章树与二叉树---二叉树的概念---应用题
- 尚硅谷MySQL学习笔记
- 程序员还差对象?new一个就行了
- @Scheduled注解详解
- 【Leetcode】479. Largest Palindrome Product
- 使用Ganache、web3.js和remix在私有链上部署并调用合约
- Special characters & escapes in bat
- 【ACWing】406. 放置机器人
猜你喜欢
随机推荐
【Leetcode】2360. Longest Cycle in a Graph
类型“FC<Props>”的参数不能赋给类型“ForwardRefRenderFunction<unknown, Props>”的参数。 属性“defaultProps”的类型不兼容。 不
[C language advanced] file operation (2)
Flink Yarn Per Job - CliFrontend
字节跳动面试官:请你实现一个大文件上传和断点续传
Docker实践经验:Docker 上部署 mysql8 主从复制
Chrome书签插件,让你实现高效整理
Appears in oozie on CDH's hue, error submitting Coordinator My Schedule
FAST-LIO2 code analysis (2)
Dynamic Scene Deblurring with Parameter Selective Sharing and Nested Skip Connections
6134. Find the closest node to the given two nodes - force double hundred code
在MySQL中使用MD5加密【入门体验】
Secondary Vocational Network Security Competition B7 Competition Deployment Process
ICLR 2022最佳论文:基于对比消歧的偏标签学习
Axure教程-新手入门基础(小白强烈推荐!!!)
伸展树的特性及实现
@Transactional 注解使用详解
邻接表与邻接矩阵
深度学习基础-基于Numpy的循环神经网络(RNN)实现和反向传播训练
企业防护墙管理,有什么防火墙管理工具?









