[LeetCode] Perfect Squares
2015-09-09 22:47
281 查看
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. This post shares a nice code and is rewritten below.
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 here.
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 here. I rewrite its clear C solution in C++ below (well, just a copy -_-).
class Solution { public: int numSquares(int n) { vector<int> dp(n + 1); iota(dp.begin(), dp.end(), 0); int ub = sqrt(n), next; for (int i = 0; i <= n; i++) { for (int j = 1; j <= ub; j++) { next = i + j * j; if (next > n) break; dp[next] = min(dp[next], dp[i] + 1); } } return dp ; } };
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 here.
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 here. I rewrite its clear C solution in C++ below (well, just a copy -_-).
class Solution { public: int numSquares(int n) { while (!(n % 4)) n /= 4; if (n % 8 == 7) return 4; for (int a = 0; a * a <= n; a++) { int b = sqrt(n - a * a); if (a * a + b * b == n) return !!a + !!b; } return 3; } };
相关文章推荐
- AngularJs 在ng-repeat中动态使用ng-model进行双向数据绑定(二)
- node.js querystring处理参数
- JavaScript词法分析过程
- javascript 的预解释机制
- Eclipse去除js(JavaScript)验证错误
- JavaScript之字符串对象
- HTML5学习笔记——1
- 剑指Offer系列---(13)二进制中1的个数
- jquery封装 [ 限制文本框只能输入数字和小数] 语句,简单调用即可
- HTML中引入资源相对路径
- JavaScript序列化和反序列化
- jquery.validate 验证
- AngularJs 在ng-repeat中动态使用ng-model进行双向数据绑定
- js中SetInterval与setTimeout用法
- Index for Html
- JavaScript随笔(二):函数只是一种对象
- 使用PhantomJS实现网页截图服务
- [杂]EXTJS 浅谈及开发过程中的理解
- populate next right pointer in each node
- 剑指Offer系列---(12)斐波那契数列