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

[Math_Medium] 279. Perfect Squares 2018-09-19

时间:2018-09-20 16:02:50      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:script   导出   tco   tor   tps   integer   esc   The   leetcode   

原题:279. 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.

题目大意:

给定一个数 n, 将其用最少的完全平方数组合出来,比如:12 = 4 + 4 + 4,因此对于输入 12,返回 3; 11 = 9 + 1 + 1,因此也返回 3.

解题思路:

我们可以列举:a[1] = 1;a[2] = a[1] + 1;a[3] = a[1] + a[1] + a[1];
a[4] = 1; a[5] = a[4] + 1; a[6] = a[4] + a[2] ...... a[8] = a[4] + a[4]
a[9] = 1;..........
即可以推导出 a[i] = min(a[i-j*j] + a[j*j]),其中, j 属于 1 到 sqrt(i)

代码如下:

class Solution {
public:
    int numSquares(int n) 
    {
       vector<int> a(n+1, 0);
        a[0] = 0;
        for(int i = 1; i <= n; i++)
        {
            int k = sqrt(i);
            k = k * k;
            if(k == i) //注意: sqrt(2)*sqrt(2) = 2
                a[i] = 1;
            else
            {
                int temp = 1<<30 - 1;
                for(int j = sqrt(i); j >= 1; j--)
                {
                    if(temp > (a[i-j*j] + a[j*j]))
                        temp = a[i-j*j] + a[j*j];
                }
                a[i] = temp;
            }
        }
        return a[n];
    }
};
  • 推导 2:因为a[j*j] == 1, 所以,a[i] = min (a[i], a[i-j*j] + 1)
    代码如下:
class Solution {
public:
    int numSquares(int n) 
    {
        vector<int> a(n+1, INT_MAX);
        a[0] = 0;
        for(int i = 1; i <= n; ++i)
        {
            for(int j = 1; j*j <= i; ++j)
            {
                a[i] = min(a[i], a[i - j*j] + 1);
            }
        }
        return a[n];
    }
};

[Math_Medium] 279. Perfect Squares 2018-09-19

标签:script   导出   tco   tor   tps   integer   esc   The   leetcode   

原文地址:https://www.cnblogs.com/qiulinzhang/p/9680756.html

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