## 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*.

For example, given *n* = `12`

, return `3`

because `12 = 4 + 4 + 4`

; given *n* = `13`

, return `2`

because `13 = 4 + 9`

.

## Analysis:

For this problem, I'd like to show the approach using BFS, and the DP. These methods is not very optimal since there is a mathematical soluiton can runs much faster. However, this problem also serves as a good practice for the BFS and DP.

The BFS approach considers finding the min numbers as a search problem. Specifically, the root node is the positive integer *n*, every time we subtract the value *n* with all the posiblle square values, which can be considered as a path from parent node to the child node. The goal is to find the shortest path, connect from root node to the node in which the value is zero. A simple way to reduce the computations is that: we could eliminate the node which we have seen before, since the path go through (if exists) the newly seen node, must not as short as any path that go through the previously seen node with same value.

The DP solution goes pretty straightforward, since for every value *n*, it must come from some value plus a square number. This can be written as:

d[n] = min(d[n - i * i] + 1), where d[n] is the least number of square numbers, and i * i <= n.

## No comments:

## Post a Comment