279. 完全平方数

解法一、回溯法:

java 复制代码
class Solution {
    public int numSquares(int n) {
        return numSquaresHepler(n);
    }
    public int numSquaresHepler(int n){
        if(n == 0) return 0;
        int count = Integer.MAX_VALUE;
        for(int i = 1; i * i <= n; i++){
            count = Math.min(count,numSquaresHepler(n - i * i) + 1);
        }
        return count;
    }
}

解法二、HashMap 优化回溯法

解法一超时,解法二优化通过使用 HashMap 保存

java 复制代码
class Solution {
    public int numSquares(int n) {
        return numSquaresHepler(n,new HashMap<Integer,Integer>());
    }
    public int numSquaresHepler(int n,HashMap<Integer,Integer> map){
        if(map.containsKey(n)) return map.get(n);
        if(n == 0) return 0;
        int count = Integer.MAX_VALUE;
        for(int i = 1; i * i <= n; i++){
            count = Math.min(count,numSquaresHepler(n - i * i,map) + 1);
        }
        map.put(n,count);
        return count;
    }
}

解法三、动态优化

递归相当于先压栈压栈然后出栈出栈,动态规划可以省去压栈的过程。

动态规划的转移方程就对应递归的过程,动态规划的初始条件就对应递归的出口。

java 复制代码
class Solution {
    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++){
             //依次减去一个平方数
            for(int j = 1; j * j <= i; j++){
                dp[i] = Math.min(dp[i],dp[i-j*j]+1);
            }
        }
        return dp[n];
    }
}
相关推荐
山甫aa8 小时前
二叉树算法-----从零开始的算法
数据结构·算法
睡觉就不困鸭8 小时前
第十七天 翻转字符串里的单词
数据结构·算法·哈希算法·散列表
ulias2128 小时前
leetcode热题 - 4
算法·leetcode·职场和发展
学术阿凡提8 小时前
Spring Boot 优雅实现异步调用:从入门到自定义线程池与异常处理
java·数据库·算法
圣保罗的大教堂8 小时前
leetcode 1559. 二维网格图中探测环 中等
leetcode
MicroTech20259 小时前
微算法科技(NASDAQ :MLGO)量子化边缘检测技术:重塑图像处理的新范式
图像处理·科技·算法
WolfGang0073219 小时前
代码随想录算法训练营 Day47 | 图论 part05
算法·图论
猿长大人9 小时前
算法 | 轮廓提取随笔 —— 关于像素、阈值和直觉的碎碎念
图像处理·算法
啦啦啦_99999 小时前
1. 线性回归之 向量&矩阵
算法·矩阵·线性回归
DolphinDB智臾科技9 小时前
DolphinDB 走进东南大学 | 新型电力系统高频数据处理与算法落地实战
算法