题目链接

完全平方数

题目描述

image.png

实现代码

动态规划思想:

  1. class Solution {
  2. public int numSquares(int n) {
  3. if(n == 1) {
  4. return 1;
  5. }
  6. int[] dp = new int[n+1];
  7. dp[1] = 1;
  8. int result = Integer.MAX_VALUE;
  9. for(int i=2; i<=n; i++) {
  10. int min = Integer.MAX_VALUE;
  11. for(int j=1; j*j <= i; j++) {
  12. min = Math.min(min, dp[i-j*j] + 1);
  13. }
  14. dp[i] = min;
  15. if(i == n) {
  16. result = Math.min(result, min);
  17. }
  18. }
  19. return result;
  20. }
  21. }