zoukankan      html  css  js  c++  java
  • 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.

    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;
        }
    }
    苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。
  • 相关阅读:
    linux如何查看ip地址
    mybais-plus整合springboot自动代码生成。
    org.springframework.beans.factory.UnsatisfiedDependencyException 问题
    springboot中使用AOP做访问请求日志
    springboot集成swagger
    springboot中的跨域问题
    spring中的ApplicationListener
    spring中的BeanDefinitionRegistryPostProcessor
    spring中的BeanFactoryPostProcessor
    servlet中ServletContainerInitializer
  • 原文地址:https://www.cnblogs.com/shaer/p/10551323.html
Copyright © 2011-2022 走看看