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

Posted qiulinzhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Math_Medium] 279. Perfect Squares 2018-09-19相关的知识,希望对你有一定的参考价值。

原题: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的主要内容,如果未能解决你的问题,请参考以下文章

[Math_Medium] 869. Reordered Power of 2

[Math_Medium]553. Optimal Division

[Math_Medium]343. Integer Break

[Math_Medium] 592. Fraction Addition and Subtraction

[Math_Medium] 781. Rabbits in Forest

[Math_Medium]462. Minimum Moves to Equal Array Elements II