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.

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.


用dfs的方法勉强过关,效率太低(380ms左右)

public class Solution {
    int min = Integer.MAX_VALUE;
    public int numSquares(int n) {
        helper(n, 0);
        return min;
    }
    
    private void helper(int n, int cnt){
        if(n==0) min = Math.min(cnt, min);
        if(cnt>=min) return;
        int m = (int)Math.sqrt(1.0*n);
        for(int i=m; i>=1; i--){
            helper(n-i*i, cnt+1);
        }
    }
}

DP的方法(46ms左右)

dp[n] indicates that the perfect squares count of the given n, and we have:

dp[0] = 0 
dp[1] = dp[0]+1 = 1
dp[2] = dp[1]+1 = 2
dp[3] = dp[2]+1 = 3
dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } 
      = Min{ dp[3]+1, dp[0]+1 } 
      = 1				
dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 } 
      = Min{ dp[4]+1, dp[1]+1 } 
      = 2
						.
						.
						.
dp[13] = Min{ dp[13-1*1]+1, dp[13-2*2]+1, dp[13-3*3]+1 } 
       = Min{ dp[12]+1, dp[9]+1, dp[4]+1 } 
       = 2
						.
						.
						.
dp[n] = Min{ dp[n - i*i] + 1 },  n - i*i >=0 && i >= 1

and the sample code is like below:

public int numSquares(int n) {
	int[] dp = new int[n + 1];
	Arrays.fill(dp, Integer.MAX_VALUE);
	dp[0] = 0;
	for(int i = 1; i <= n; ++i) {
		int min = Integer.MAX_VALUE;
		int j = 1;
		while(i - j*j >= 0) {
			min = Math.min(min, dp[i - j*j] + 1);
			++j;
		}
		dp[i] = min;
	}		
	return dp[n];
}

数学的计算方法(2ms)

public class Solution { //四平方定理,任何一个正整数都可以表示成不超过四个整数的平方之和
    public int numSquares(int n) {
        while (n % 4 == 0) n /= 4;  //网上找到的定理,并不会证明
        if (n % 8 == 7) return 4;
        for (int a = 0; a * a <= n; a++) {
            int b = (int)Math.sqrt(n - a * a);
            if (a * a + b * b == n) {
                if(a>0 && b>0){
                    return 2;
                }else{
                    return 1;
                }
            }
        }
        return 3;
    }
}

From Wikipedia, the free encyclopedia

In mathematicsLegendre's three-square theorem states that a natural number can be represented as the sum of three squares of integers

{\displaystyle n=x^{2}+y^{2}+z^{2}}n=x^{2}+y^{2}+z^{2}

if and only if n is not of the form {\displaystyle n=4^{a}(8b+7)}n = 4^a(8b + 7) for integers a and b.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值