From 75ef39813b6b19baf2fdbc44dfd8018d890e7473 Mon Sep 17 00:00:00 2001 From: Kiril Kovachev Date: Fri, 8 Mar 2024 19:25:59 +0000 Subject: [PATCH] Solve 279. Perfect Squares --- python/277_perfect_squares.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 python/277_perfect_squares.py diff --git a/python/277_perfect_squares.py b/python/277_perfect_squares.py new file mode 100644 index 0000000..2952389 --- /dev/null +++ b/python/277_perfect_squares.py @@ -0,0 +1,15 @@ +class Solution: + def numSquares(self, n: int) -> int: + # Possible square numbers we can choose from (all squares below n) + squares_below = list(takewhile(lambda x: x <= n, (n ** 2 for n in count(1)))) + + # Once this has been solved, it's basically just the same as 322. Coin Change + minimum_to_make = [(n+1)] * (n + 1) # List where the i'th index gives the number of squares required to make i + minimum_to_make[0] = 0 + for i in range(n + 1): + for num in squares_below: + remainder = i - num + if remainder >= 0: + minimum_to_make[i] = min(minimum_to_make[i], minimum_to_make[remainder] + 1) + + return minimum_to_make[-1]