279. Perfect Squares

Posted 我的名字叫周周

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了279. Perfect Squares相关的知识,希望对你有一定的参考价值。

    /*
     * 279. Perfect Squares
     * 2016-6-26 by Mingyang 
     * 同样的道理,这里的options就是所有比自己小的perfect square
     * numbers dp[n] indicates that the perfect squares count of the given n,
     * and we have: 
     * dp[0] = 0 
     * dp[1] = dp[0]+1 = 1 
     * dp[2] = dp[1]+1 = 2 
     * dp[3] =dp[2]+1 = 3 
     * dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } 
     *      = Min{ dp[3]+1,dp[0]+1 } 
     *       = 1 
     * dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 } 
     *      = Min{ dp[4]+1,dp[1]+1 } 
     *       = 2 
     * dp[13] = Min{ dp[13-1*1]+1, dp[13-2*2]+1,dp[13-3*3]+1 } 
     *        = Min{ dp[12]+1, dp[9]+1, dp[4]+1 } 
     *        = 2 
     *  dp[n] = Min{dp[n - i*i] + 1 }, n - i*i >=0 && i >= 1
     */
      public int numSquares(int n) {
             int sq=0;
             int[] dp=new int[n+1];
             dp[0]=0;
             dp[1]=1;
             for(int i=2;i<=n;i++)
            {
              dp[i]=i;
              for(int j=1;j*j<=i;j++)
              {
                 dp[i]=Math.min(dp[i],dp[i-j*j]+1);
               }
            }
            return dp[n];
       } 

 

以上是关于279. Perfect Squares的主要内容,如果未能解决你的问题,请参考以下文章

279. Perfect Squares

279. Perfect Squares

279. Perfect Squares

LeetCode 279. Perfect Squares

leetcode279 Perfect Squares

LeetCode 279. Perfect Squares