https://leetcode.com/problems/perfect-squares/
Understanding:
Can have number theory, DP, BFS Three kinds of ideas to solve,
Number theory: recommended in this way
In this ref, it's a detailed story.
Http://www.cnblogs.com/grandyang/p/4800552.html
Solution II: Dynamic Programming (programming)
Time complexity: O (n * sqrt N)
Initialize the DP array to infinity; Dp[y * y] = 1, where: Y * y <= N. This means that the square is itself, so of course it turns out to be 1.
State transition equation:
Dp[x + y * y] = min (dp[x + y * y), dp[x] + 1)
Wherein: DP [i] represents the minimum number of squares and numbers required to gather into I, and x + y * y <= N
The transfer formula is dp[n] = 1 + min ([dp[n-j**2] for J-xrange (1, int (n**0.5) + 1)], which is the number of the current n corresponding Perfect square minus one, minus a perfect sq Uare, the rest must also have the least perfect square part, and the perfect square, which is to be subtracted, cannot be reduced arbitrarily, at most, minus its own sqrt
This version leetcode not allowed, timeout
Class Solution (object):
def numsquares (self, N): ""
: Type n:int
: Rtype:int ""
"
if n<=0: Return
0
DPS = [0]
for i in xrange (1, n + 1):
tmp = 1 + min ([dp[i-j * 2] for J-xrange (1, int (i**0.5 ) + 1)])
dp.append (TMP) return
Dp[-1]
But the mind is right.
Reference code: http://bookshadow.com/weblog/2015/09/09/leetcode-perfect-squares/
Http://traceformula.blogspot.hk/2015/09/perfect-squares-leetcode.html
BFS:
Extensive search:
Http://traceformula.blogspot.hk/2015/09/perfect-squares-leetcode.html