Leetcode 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.

 

 1 public class Solution {
 2     public int NumSquares(int n) {
 3         var dp = new int[n + 1];
 4         dp[0] = 0;
 5         
 6         for (int i = 1; i <= n; i++)
 7         {
 8             dp[i] = Int32.MaxValue;
 9             for (int j = 1; j <= i / j; j++)
10             {
11                 dp[i] = Math.Min(dp[i], dp[i - j * j] + 1);
12             }
13         }
14         
15         return dp[n];
16     }
17 }

 

posted @ 2017-12-07 03:05  逸朵  阅读(98)  评论(0编辑  收藏  举报