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];
    }
}
相关推荐
月疯13 分钟前
二分法算法(水平等分图形面积)
算法
豆瓣鸡25 分钟前
算法日记 - Day3
java·开发语言·算法
白白白小纯37 分钟前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang1 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
The Chosen One9851 小时前
高进度算法模板速记(待完善)
java·前端·算法
圣保罗的大教堂3 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode
土豆.exe4 小时前
Fastjson2 2.0.53 哈希碰撞 RCE:从原理到三种打法
算法·哈希算法
黄河123长江4 小时前
有限Abel群的结构()
算法
Jerry4 小时前
LeetCode 92. 反转链表 II
算法
骊城英雄5 小时前
Rust从入门到精通-trait
人工智能·算法·rust