原题链接在这里:https://leetcode.com/problems/perfect-squares/

题目:

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

题解:

Let dp[i] denotes the least number of perfect squares sum to i.

Then for all the candiates smaller than i, if the difference between i and candidate is perfect square, then update the dp[candidate]+1. Maintain the smallest.

Thne how to make sure the difference is perfect square.

Let candidate = i - j*j.

Time Complexity: O(nlogn).

Space: O(n).

AC Java:

 class Solution {
public int numSquares(int n) {
int [] dp = new int[n+1];
for(int i = 1; i<=n; i++){
dp[i] = i;
for(int j = 0; i-j*j>=0; j++){
dp[i] = Math.min(dp[i], dp[i-j*j]+1);
}
} return dp[n];
}
}

Could also do it from head to tail.

初始化i*i的位置为1, 然后对i + j*j 更新min(dp[i+j*j], dp[i] + 1).

Time Complexity: O(nlogn). Space: O(n).

AC Java:

 public class Solution {
public int numSquares(int n) {
if(n < 0){
return 0;
}
int [] dp = new int[n+1];
Arrays.fill(dp, Integer.MAX_VALUE);
for(int i = 0; i*i <= n; i++){
dp[i*i] = 1;
}
for(int i = 1; i<=n; i++){
for(int j = 1; i+j*j<=n; j++){
dp[i+j*j] = Math.min(dp[i+j*j], dp[i]+1);
}
}
return dp[n];
}
}

Count Primes类似.

最新文章

  1. Python2.7&lt;--------&gt;Python3.x
  2. Kafka/Metaq设计思想学习笔记 转
  3. Redis操作+python
  4. linux shutdown关闭系统命令使用介绍(转)
  5. SecureCRT的相关问题
  6. Apache、tomcat、Nginx常用配置合集
  7. 企业网站DDOS防护解决方案
  8. Stored Procedures with Multiple Result Sets
  9. Web.xml 中增加log4j
  10. 解决VirtualBox错误:“FATAL:No bootable medium found!”
  11. MYSQL管理之主从同步管理 转载
  12. IOS系列——NStimer
  13. Tomcat+Eclipse乱码问题解决方法
  14. ES6(let.contest命令)
  15. python面试题一个字符串是否由重复的子字符串组成
  16. 1.1.4 PROB Greedy Gift Givers
  17. elasticsearch概念及倒排索引简单介绍
  18. POJ3734Blocks(递推+矩阵快速幂)
  19. 用vs调试sql存储过程
  20. iOS APP网络分析之rvictl(可以捕捉除了Wifi以外的网络类型)

热门文章

  1. 通过JDBC连接hive
  2. CSS3时钟式进度条
  3. 在client类中设置访问属性 address,business和individua
  4. 获取Dell,Lenovo电脑的保修期
  5. Jersey MVC
  6. 解决电脑访问Discuz!手机版(支持触屏版)
  7. PHP文件操作 之打开远程文件
  8. cluster analysis in data mining
  9. ArcGIS Server发布服务,打包成功,发布失败
  10. Windows 下 Nginx + PHP + Xdebug + PHPStorm 调试环境配置