Last active
March 7, 2022 16:24
-
-
Save ibeauregard/66f2db7f5c663683dc68ea501b0221fc to your computer and use it in GitHub Desktop.
Given an integer 'target', return the least number of perfect square numbers that sum to n.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import sqrt | |
def numSquares(target): | |
squares = [n ** 2 for n in range(1, int(sqrt(target)) + 1)] | |
level = 0 | |
remainders = {target} | |
while True: | |
level += 1 | |
next_remainders = set() | |
for remainder in remainders: | |
for square in squares: | |
if square == remainder: | |
return level | |
if square > remainder: | |
break | |
next_remainders.add(remainder - square) | |
remainders = next_remainders |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment