[LeetCode] Perfect Squares
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.
1 class Solution { 2 public: 3 int numSquares(int n) { 4 vector<int> 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 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 -_-).
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 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档