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];
    }
}
相关推荐
蒟蒻小袁29 分钟前
力扣面试150题--被围绕的区域
leetcode·面试·深度优先
Q8137574601 小时前
中阳视角下的资产配置趋势分析与算法支持
算法
yvestine1 小时前
自然语言处理——文本表示
人工智能·python·算法·自然语言处理·文本表示
GalaxyPokemon1 小时前
LeetCode - 148. 排序链表
linux·算法·leetcode
iceslime2 小时前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析
aichitang20243 小时前
矩阵详解:从基础概念到实际应用
线性代数·算法·矩阵
OpenCSG3 小时前
电子行业AI赋能软件开发经典案例——某金融软件公司
人工智能·算法·金融·开源
chao_7894 小时前
链表题解——环形链表 II【LeetCode】
数据结构·leetcode·链表
dfsj660114 小时前
LLMs 系列科普文(14)
人工智能·深度学习·算法
薛定谔的算法5 小时前
《盗梦空间》与JavaScript中的递归
算法