Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

Example 1:

Input: n = 12
Output: 3 
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

这道题考察的是 四平方定理

如果一个数字余8等于7 则这个数一定能被四个完全平方数表示
如果一个数字余4为0 则说明这个数字可以被三个完全平方数表示
int numSquares(int n){
    while(n % 4 == 0) n /= 4;       
    if(n % 8 == 7) return 4;
    int a = 0;
    for(a = 0; a  * a <= n; a++)
    {
        int b = sqrt(n - a*a);
        if(a * a + b * b == n)
            return !!a + !!b;
        
    }
    
    
    return 3;

}

当然当我们不知道四平方定理的时候 我们得运用一些其他方法去求证。


posted on 2020-04-19 11:06  闲云潭影  阅读(534)  评论(0编辑  收藏  举报