Skip to content

Latest commit

 

History

History
41 lines (33 loc) · 1.25 KB

279.-perfect-squares.md

File metadata and controls

41 lines (33 loc) · 1.25 KB

279. Perfect Squares

  • Medium

  • Given an integer n, return the least number of perfect square numbers that sum to n.

    A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Analysis

A BFS would give the solution to this problem. In searching, we want to see if a level of the tree can satisfy the result, if not, we move on to the next level with one more number to add. The tree would look like the following:

class Solution:
    def numSquares(self, n):
        if n < 2:
            return n
        lst = []
        i = 1
        while i * i <= n:
            lst.append( i * i )
            i += 1
        cnt = 0
        toCheck = {n}
        while toCheck:
            cnt += 1
            temp = set()
            for x in toCheck:
                for y in lst:
                    if x == y:
                        return cnt
                    if x < y:
                        break
                    temp.add(x-y)
            toCheck = temp

        return cnt