博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Perfect Squares
阅读量:4686 次
发布时间:2019-06-09

本文共 1708 字,大约阅读时间需要 5 分钟。

Well, after seeing the similar problems, you may have known how to solve this problem. Yeah, just to construct larger numbers from smaller numbers by adding perfect squares to them. shares a nice code and is rewritten below.

1 class Solution { 2 public: 3     int numSquares(int n) { 4         vector
dp(n + 1); 5 iota(dp.begin(), dp.end(), 0); 6 int ub = sqrt(n), next; 7 for (int i = 0; i <= n; i++) { 8 for (int j = 1; j <= ub; j++) { 9 next = i + j * j;10 if (next > n) break;11 dp[next] = min(dp[next], dp[i] + 1);12 }13 }14 return dp[n];15 }16 };

Well, you may have noticed that the above code has many repeated computations. For example, for n = 10 and 11, we will recompute dp[0] to dp[10]. So a way to reduce the running time is to use static variables to store those results and return it if it has already been computed. Stefan posts severl nice solutions .

Finally, the above strategy using static variables does not reduce the expected running time of the algorithm, which is still of O(n^(3/2)). And guess what? There exists a much faster O(n^(1/2)) algorithm using number theory, also posted by Stefan . I rewrite its clear C solution in C++ below (well, just a copy -_-).

1 class Solution { 2 public: 3     int numSquares(int n) { 4         while (!(n % 4)) n /= 4; 5         if (n % 8 == 7) return 4; 6         for (int a = 0; a * a <= n; a++) { 7             int b = sqrt(n - a * a); 8             if (a * a + b * b == n) 9                 return !!a + !!b;10         }11         return 3;12     }13 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4796240.html

你可能感兴趣的文章
第一次使用maven记录
查看>>
SharePoint服务器端对象模型 之 使用CAML进展数据查询
查看>>
Building Tablet PC Applications ROB JARRETT
查看>>
Adobe® Reader®.插件开发
查看>>
【POJ 3461】Oulipo
查看>>
Alpha 冲刺 (5/10)
查看>>
使用Siege进行WEB压力测试
查看>>
斑马为什么有条纹?
查看>>
android多层树形结构列表学习笔记
查看>>
Android_去掉EditText控件周围橙色高亮区域
查看>>
《构建之法》第一、二、十六章阅读笔记
查看>>
Pandas基础(十一)时间序列
查看>>
arrow:让Python的日期与时间变的更好
查看>>
MySQL命令行参数
查看>>
MFC中 用Static控件做超链接(可以实现变手形、下划线、字体变色等功能)
查看>>
20144303 《Java程序设计》第五周学习总结
查看>>
多线程(第三天)
查看>>
python 抓取小说网站,制作电子书。
查看>>
restframework视图三部曲
查看>>
失去光标display=none事件的坑
查看>>