279 Perfect Squares
Given a positive integern, find the least number of perfect square numbers (for example,1, 4, 9, 16, ...
) which sum ton.
For example, givenn=12
, return3
because12 = 4 + 4 + 4
; givenn=13
, return2
because13 = 4 + 9
.
Approach 1: DFS
The Idea: Find the smallest path from root to leaf. Let squares be all the perfect squares that are less than n. Begin with the root node as n, and define all children of n to be n-squares[i]
. Continue this process until a remainder of 0 is reached. Lagrange's four-square theorem tells us that this number will always be less than or equal to 4 (
every natural number can be represented as the sum of four integer squares). Return the minimum path length. This is bad approach because it prioritizes the depth of the tree when it is a smarter to equally weight the branches closest to the root.
Approach 2: BFS
Last updated