# 279. Perfect Squares https://leetcode.com/problems/perfect-squares/ ###### Medium ##### Description > Given an integer n, return the least number of perfect square numbers that sum to n. > > A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not. ##### Example1 > Input: n = 12 > Output: 3 > Explanation: 12 = 4 + 4 + 4. ##### Example2 > Input: n = 13 > Output: 2 > Explanation: 13 = 4 + 9. ##### Solution ```kotlin= class Solution { fun numSquares(n: Int): Int { val dp = Array(n + 1) { Int.MAX_VALUE } dp[0] = 0 for (i in 1 until dp.size) { dp[i] = dp[i - 1] + 1 var j = 1 while (i - j * j >= 0) { dp[i] = minOf(dp[i], dp[i - j * j] + 1) j++ } } return dp[n] } } ``` ##### Tips * Dynamic programming ##### Note dp[0] = 0 dp[1] = dp[0]+1 dp[2] = dp[2-1^2]+1 ... dp[4] = dp[4-1^2]+1 or dp[4-2^2]+1 dp[5] = dp[5-1^2]+1 or dp[5-2^2]+1 ... dp[8] = dp[8-1^2]+1 or dp[8-2^2]+1 dp[9] = dp[9-1^2]+1 or dp[9-2^2]+1 ... dp[11] = dp[11-1^2]+1 or dp[11-2^2]+1 or dp[11-3^2]+1 dp[12] = dp[12-1^2]+1 or dp[12-2^2]+1 or dp[12-3^2]+1