279. Perfect Squares(完美平方数)

博客围绕给定正整数n,探讨求其最少完美平方数之和的问题。介绍了一种方法,时间复杂度为o(n^2),空间复杂度为o(n),还提及bfs方法,以n为顶点、完美平方数为每一层发散,用dp数组记录点所在层数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
方法一:动态规划:
分析:根据动态规划分析得,偶了每一个数都可以看成是一个完美平方+一个普通数。即x=a*a+b。或者这个数本身就是完全平方,例如1,4,9,16等。那么动态规划的公式就
有了:dp[i+j*j]=min(dp[i]+1,dp[i+j*j])

时间复杂度:o(n^2)                空间复杂度:o(n)

 方法二:bfs

本方法的主要思想是,以n为顶点,完美平方数为每一层发散。先设定完美平方数对应的点为第一层(例如1,4,9...)

dp数组用来存放该点在第几层,例如完美平方数在第一层。2,5,8,10在第二层等。

以n=12为例分析得:

第一个for循环先将完美平方数对应的设为1,默认为第一层。并以次加入队列。

 

class Solution {
    public int numSquares(int n) {
        Queue<Integer> queue = new LinkedList<Integer>();
        if (n < 1) return 0;
        int[] dp = new int[n + 1];
        for (int i = 1; i * i <= n; i++) {
            if (i * i == n) return 1;
            dp[i * i] = 1;
            queue.add(i * i); //把完美平方数加入到队列 1,4,9
        }
        while (!queue.isEmpty()) {
            int cur = queue.peek();
            for (int i = 1; i * i <=n - cur; i++) {
                if (cur + i * i == n) {
                    return dp[cur] + 1;
                } else if ((cur + i * i < n) && (dp[cur + i * i] == 0)) { //不在队列中就加入队列
                    dp[cur + i * i] = dp[cur] + 1;
                    queue.add(cur + i * i);
                } else if (cur + i * i > n) {
                    break;
                }
            }
            queue.poll();
        }
        return 0;
    }
}

 

转载于:https://www.cnblogs.com/shaer/p/10551323.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值