当前位置:网站首页>【刷题篇】完全平方数
【刷题篇】完全平方数
2022-07-17 05:58:00 【m0_60631323】
一、题目
OJ链接
给你一个整数 n ,返回 和为 n 的完全平方数的最少数量 。
完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,1、4、9 和 16 都是完全平方数,而 3 和 11 不是。
二、题解
2.1 数学解
规律:
- 四平方和定理:每个正整数都可以表示为至多4个正整数的平方和。
- 任何消掉4的因子,结论不变
- 模8等于7的数,一定是有四个数的平方和组成
public int numSquares(int n) {
while (n%4==0){
n=n/4;
}
if(n%8==7){
return 4;
}
for (int a = 0; a*a<=n ; a++) {
int b=(int)Math.sqrt(n-a*a);
if(a*a+b*b==n){
return (a>0&&b>0)?2:1;
}
}
return 3;
}
2.2 动态规划

public int numSquares(int n) {
int[] dp = new int[n + 1]; // 默认初始化值都为0
for (int i = 1; i <= n; i++) {
dp[i] = i; // 最坏的情况就是每次+1
for (int j = 1; i - j * j >= 0; j++) {
dp[i] = Math.min(dp[i], dp[i - j * j] + 1); // 动态转移方程
}
}
return dp[n];
}
边栏推荐
- Introduction & use of Maxwell
- Redis源码分析之双索引机制
- 4-channel FMC interface baseband signal processing board (2 FMC interfaces, 2 fmc+ interfaces)
- Redis storage structure principle 2
- TSN security protocol (802.1qci)
- PyCharm 界面设置
- 175. 组合两个表(MySQL数据库连接)
- redis分布式锁
- @How can conditionalonmissingbean cover beans in third-party components
- Comparative analysis of the differences between nor and NAND
猜你喜欢

High performance integrated video image processing board based on ultrascale FPGA + Huawei Hisilicon arm / fpga+arm

Use of mongodb

912. 排序数组(数组排序)

Pytorch notes (5)

Spark3.x entry to mastery - stage 7 (spark dynamic resource allocation)

Pytorch随记(2)

怎么检查APP是否存在用户信息数据泄露漏洞

Jd.com's purchase intention forecast (III)

Flutter3.0 (framework) - UI rendering

Modify radio style
随机推荐
导出文件or下载文件
4-channel fmc+ baseband signal processing board (4-channel 2G instantaneous bandwidth ad+da)
看完代码回首看论文:YOLOv3重读
MongoDB的使用
Convolutional neural network CNN
Modify scroll bar style
【MySQL】 锁机制:InnoDB引擎中锁分类以及表锁、行锁、页锁详解
Forecast sales xgboost
网站APP数据库里的用户信息被泄露篡改怎么办
How to choose the right model
神经网络和自动控制的联系
Using PCA to simplify data
收单外包服务商北京捷文科技以约4.8亿转让60%股份
【MySQL】 事务:事务基础知识、MySQL事务实现原理、事务日志 redolog & undolog 详解
How to write the highlights of SCI papers (seriously teach you how to write)
pytorch随记(5)
[day01] preface, introductory program, constant variables
Ku115 FPGA high performance 10G Optical fiber network hardware accelerator card / 2-way 10G Optical fiber data accelerator card
Jd.com's purchase intention forecast (IV)
利用PCA来简化数据