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:

  1. Dynamic Programming

    1. sq[i] = ... to number i

    2. sq[0] = 0

    3. search from 1 to j (j ^2 <= i): sq[i] = min(sq[i], sq[i-j^2] + 1)

  2. Static Dynamic Programming

    1. sq[i]: ... to number i

    2. sq[0] = 0

    3. in the loop, each time push the result for sq[i] into ith of the container.

  3. Mathematical Solution

    1. Lagrange's Four Square Theorem: Any natural number can be represented by the sum of at most 4 perfect square numbers

    2. number that need 4 perfect square meets: 4^k(8m + 7)

  4. BFS

    1. Each node a number

    2. 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)

from zhukov's post

Last updated

Was this helpful?