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.
Example 1:
Input:
n = 12
Output: 3
Explanation:
12 = 4 + 4 + 4.Example 2:
Input:
n = 13
Output: 2
Explanation:
13 = 4 + 9.Thoughts:
Dynamic Programming
sq[i] = ... to number i
sq[0] = 0
search from 1 to j (j ^2 <= i): sq[i] = min(sq[i], sq[i-j^2] + 1)
Static Dynamic Programming
sq[i]: ... to number i
sq[0] = 0
in the loop, each time push the result for sq[i] into ith of the container.
Mathematical Solution
Lagrange's Four Square Theorem: Any natural number can be represented by the sum of at most 4 perfect square numbers
number that need 4 perfect square meets: 4^k(8m + 7)
BFS
Each node a number
An edge between i and j exists if from node i to j, there is only one perfect number away.
Code 1:
Code 2:
Code 3: Lagrange's Four Square Theorem
Code 4: BFS: O(n*E)
Last updated
Was this helpful?