解法一、回溯法:
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 保存
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;}
}
解法三、动态优化
递归相当于先压栈压栈然后出栈出栈,动态规划可以省去压栈的过程。
动态规划的转移方程就对应递归的过程,动态规划的初始条件就对应递归的出口。
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];}
}