zoukankan      html  css  js  c++  java
  • 0279. Perfect Squares (M)

    Perfect Squares (M)

    题目

    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个完全平方数的和,求x的最小值。

    思路

    直接使用递归会超时,使用记忆化搜索进行优化。

    也可以使用动态规划:dp[i]表示整数i最少由dp[i]个完全平方数相加得到,dp[i]初始值为1(自己就是完全平方数)或i(由i个1相加得到),递推公式为:(dp[i]=Math.min(dp[i], dp[j] + dp[i-j]))


    代码实现

    Java

    记忆化搜索

    class Solution {
        public int numSquares(int n) {
            int[] record = new int[n + 1];
            Arrays.fill(record, -1);
            return dfs(n, record);
        }
    
        private int dfs(int n, int[] record) {
            if (n <= 1) {
                return n;
            }
    
            if (record[n] != -1) {
                return record[n];
            }
    
            int min = n;
            for (int i = 1; i * i <= n; i++) {
                min = Math.min(min, dfs(n - i * i, record));
            }
    
            record[n] = min + 1;
            return min + 1;
        }
    }
    

    动态规划

    class Solution {
        public int numSquares(int n) {
            int[] dp = new int[n + 1];
            dp[1] = 1;
            for (int i = 2; i <= n; i++) {
                int root = (int) Math.sqrt(i);
                dp[i] = root * root == i ? 1 : i;
                for (int j = 1; j <= i / 2; j++) {
                    dp[i] = Math.min(dp[i], dp[i - j] + dp[j]);
                }
            }
            return dp[n];
        }
    }
    
  • 相关阅读:
    配置Keepalived双主热备
    配置 Keepalived
    Keepalived安装部署
    Keepalived配置Nginx自动重启
    Collectiont和Collections的区别
    HashMap和Hashtable的联系和区别
    Vector和ArrayList的联系和区别
    ArrayList和LinkedList 的联系和区别
    集合和数组的比较
    struts下载
  • 原文地址:https://www.cnblogs.com/mapoos/p/13171311.html
Copyright © 2011-2022 走看看