#279 Perfect Squares

Description

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Examples

Example 1:

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

Example 2:

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

Constraints:

1 <= n <= 1 0 4 10^4 104

思路

最开始就是dp的思路,这里因为给出了constraints,所以有两种方案,一种是对每个数字都判断一遍是不是square,然后向前做dp;还有一种是预先算好所有的perfectSquare,再逐一判断,后者能比前者快5倍。

但后来发现有mathematic ways,就是一个数最多由4个完全平方数组成,而且各自的情况都可以枚举

  • 4-square theorem
    如果 n 是 4 的倍数,那 n 的组成和 n / 4 的组成一致
  • 3-square theorem
    如果 n 除 8 余 7,那 n 由 4 个完全平方数组成
  • 余下的数字,要么由 2 个完全平方数组成,要么由 3 个完全平方数组成,通过枚举判断

代码

DP1

class Solution {
    
    public int numSquares(int n) {
        List<Integer> perfectSquare = new ArrayList<>();
        int[] save = new int[n + 1];
        save[0] = 0;
        
        for (int i = 1; i <= n; i++){
            if (Math.sqrt(i) == (int)Math.sqrt(i)){
                save[i] = 1;
                perfectSquare.add(i);
            }
            
            save[i] = Integer.MAX_VALUE;
            for (int ps: perfectSquare){
                save[i] = Math.min(save[i], save[i - ps] + 1);
            }
        }
        
        return save[n];
    }
}

DP1

class Solution {
    
    public int numSquares(int n) {
        int[] perfectSquare = new int[100];
        int[] save = new int[n + 1];
        save[0] = 0;
        
        for (int i = 1; i < 101; i++) {
            perfectSquare[i - 1] = i * i;
        }
        
        for (int i = 1; i <= n; i++){
            save[i] = Integer.MAX_VALUE;
            for (int j = 0; (perfectSquare[j] <= i && j < 100); j++){
                save[i] = Math.min(save[i], save[i - perfectSquare[j]] + 1);
            }
        }
        
        return save[n];
    }
}

Mathematic

class Solution {
    boolean isSquare(int n) {
        int sq = (int) Math.sqrt(n);
        return n == sq * sq;
    }

    public int numSquares(int n) {
        // four-square and three-square theorems.
        while (n % 4 == 0)
            n /= 4;
        if (n % 8 == 7)
            return 4;

        if (this.isSquare(n))
            return 1;
        // enumeration to check if the number can be decomposed into sum of two squares.
        for (int i = 1; i * i <= n; ++i) {
            if (this.isSquare(n - i * i))
                return 2;
        }
        // bottom case of three-square theorem.
        return 3;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值