The question arises:
For a positive integer n, we find the smallest number of perfect square numbers (for example, 1, 4, 9, 16, ...) that add up to n. Question link
Example
Given n = 12, return 3 because 12 = 4 + 4 + 4; if n = 13, return 2 because 13 = 4 + 9.
NOTE
The approach I made is similar to the Integer Knackack task with valid duplicates . First, I calculated all perfect squares that are less than the number n. Now that I have them, the problem is similar to the Integer Knapsack problem. I have a number n and a list of numbers. I want to select the minimum number of numbers from the list so that their sum is n. This problem has a DP solution that I used.
Out of 586 test cases, I went through 562 test cases and got a TLE in the following. The n value for this test is 3428.
Solution presented by me:
class Solution(object):
def numSquares(self,n):
if(n == 0):
return 0
if(n == 1):
return 1
squares = self.findSquares(n)
rows = len(squares)
cols = n + 1
mat = []
for i in range(rows):
mat.append([0] * cols)
for i in range(cols):
mat[0][i] = i
for i in range(rows):
mat[i][0] = 0
min = mat[0][cols - 1]
for i in range(1,rows):
for j in range(1,cols):
if(j < squares[i]):
mat[i][j] = mat[i - 1][j]
else:
mat[i][j] = self.min(mat[i - 1][j], (j // squares[i] + (mat[i][j % squares[i]])))
if(j == cols - 1 and mat[i][j] < min):
min = mat[i][j]
'''
for i in range(rows):
for j in range(cols):
print(mat[i][j],end=" ")
print()
'''
return min
def min(self,a,b):
if(a <= b):
return a
else:
return b
def findSquares(self,n):
i = 1
squares = []
while (i * i <= n):
squares.append(i * i)
i = i + 1
return squares
'''
x = Solution()
print(x.numSquares(43))
'''
Thanks in advance.
source
share