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];
    }
}
相关推荐
wadesir2 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust
yugi9878382 小时前
基于MATLAB实现协同过滤电影推荐系统
算法·matlab
TimberWill2 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit2 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
leoufung2 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
wifi chicken3 小时前
数组遍历求值,行遍历和列遍历谁更快
c语言·数据结构·算法
胡楚昊3 小时前
NSSCTF动调题包通关
开发语言·javascript·算法
Gold_Dino4 小时前
agc011_e 题解
算法
bubiyoushang8884 小时前
基于蚁群算法的直流电机PID参数整定 MATLAB 实现
数据结构·算法·matlab
风筝在晴天搁浅4 小时前
hot100 240.搜索二维矩阵Ⅱ
算法·矩阵