LeetCode 279. Perfect Squares(完美平方)

原题网址:https://leetcode.com/problems/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.

方法一:动态规划。这是一道非常非常典型的动态规划问题。

1. 首先如何定义问题?这个问题就是,f(i)=对于任意一个正整数i,求i由多少个整数平方和组成。

2. 如何得到最终问题f(n)?方法就是从1开始计算,f(1),f(2),直到f(n)

3. 每个f(i)如何计算?每个f(i)只和前面的f值有关!!!

public class Solution {
    public int numSquares(int n) {
        int[] nums = new int[n+1];
        for(int i=1; i<=n; i++) nums[i] = i;
        for(int i=2; i<=n; i++) {
            for(int j=1; j*j<=i; j++) {
                nums[i] = Math.min(nums[i], nums[i-j*j]+1);
            }
        }
        return nums[n];
    }
}

方法二:非常变态,用到“四平方和定理”

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) return (a==0?0:1) + (b==0?0:1);
        }
        
        return 3;
    }
}

我没有做出来,参考:

http://storypku.com/2015/10/leetcode-question-279-perfect-squares/

https://zh.wikipedia.org/wiki/%E5%9B%9B%E5%B9%B3%E6%96%B9%E5%92%8C%E5%AE%9A%E7%90%86

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值