zoukankan      html  css  js  c++  java
  • 279. Perfect Squares

    Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

    For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

    本题可以使用DP来做,也可以使用BFS来做;

    如果使用DP来做,则需要推算出状态方程,这里面的状态方程开始并没有想出来,看了答案后才做出来,代码如下:

     1 public class Solution {
     2     public int numSquares(int n) {
     3         int[] dp = new int[n+1];
     4         Arrays.fill(dp,Integer.MAX_VALUE);
     5         dp[0] = 0;
     6         for(int i=1;i<=n;i++){
     7             for(int j=1;j*j<=i;j++){
     8                 dp[i] = Math.min(dp[i],dp[i-j*j]+1);
     9             }
    10         }
    11         return dp[n];
    12     }
    13 }
  • 相关阅读:
    python bif 如何自学
    python萌新应知应会
    Animation
    响应式布局
    浏览器兼容
    HTML基础
    SublimeText 3 Emmet Hot Keys
    Web大前端环境搭建
    Sublime Text 运行js
    bash脚本编程基础
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6551649.html
Copyright © 2011-2022 走看看