当前位置:网站首页>【刷题篇】完全平方数
【刷题篇】完全平方数
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];
}
边栏推荐
- redis事务
- C语言一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2+3.编程
- [MySQL] transaction: basic knowledge of transaction, implementation principle of MySQL transaction, detailed explanation of transaction log redolog & undo
- SCI论文的Highlights怎么写(正经的教你怎么写)
- 修改滚动条样式
- 【MySQL】 锁机制:InnoDB引擎中锁分类以及表锁、行锁、页锁详解
- How to associate the application on enterprise wechat with the Sybase database of the store
- 力扣114题:二叉树展开链表
- 怎么检查APP是否存在用户信息数据泄露漏洞
- fiddler 抓包工具使用
猜你喜欢

Using PCA to simplify data

How to choose flash for new products?

导出文件or下载文件

openvino机器学习初体验

redis主从复制

Xiaoyi and you talk about how to realize c-v2x HIL test in v2x test series (2022 version)

How does continuous integration manage Jenkins?

Pytorch随记(2)

175. Combine two tables (MySQL database connection)

912. 排序数组(数组排序)
随机推荐
SCI论文的Highlights怎么写(正经的教你怎么写)
Pytoch notes (1)
养老年金保险有必要买吗?适合老人的养老年金产品有哪些?
175. Combine two tables (MySQL database connection)
Spark3.x source code compilation
Pytorch随记(3)
[MySQL] transaction: basic knowledge of transaction, implementation principle of MySQL transaction, detailed explanation of transaction log redolog & undo
60. Clear cache
pytorch随记(5)
INSTALL_ PARSE_ FAILED_ MANIFEST_ MALFORMED
修改radio样式
Regular expression extraction of matching content
机器学习面试题(转载)
fiddler 抓包工具使用
收单外包服务商北京捷文科技以约4.8亿转让60%股份
C语言一个数如果恰好等于它的因子之和,这个数就称为“完数”。例如6=1+2+3.编程
standard-version(发版与 Changelog 自动化)
Pytorch notes (5)
机器学习之随机森林
1669. 合并两个链表(两个链表的合并)