码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Perfect Squares

时间:2015-09-10 00:16:07      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

[LeetCode] Perfect Squares

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4796240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!