imashutosh51

Perfect squares

Oct 16th, 2022 (edited)
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. '''
  2. For a number n, we only need to consider numbers from 1 to sqrt(n) because any number larger than sqrt(n) will have a square greater than n and therefore cannot contribute to the sum. For example, if n = 25, then the possible numbers are 1, 2, 3, 4, 5, whose squares are 1, 4, 9, 16, 25. The problem then becomes finding the minimum number of these square values whose sum equals n. So this problem is essentially similar to the Minimum Coin Change or Minimum Denominations problem, where the square numbers act like coins and we need the minimum number of coins to form the target sum.'''
  3.  
  4. import math
  5. def fun(index,current_sum,numbers,dp,target):
  6.     if current_sum==target:
  7.         return 0
  8.        
  9.     if index<0 or current_sum>target: #as this is not a valid case
  10.         return math.inf
  11.        
  12.     if dp[index][current_sum]!=-1:
  13.         return dp[index][current_sum]
  14.  
  15.     take=math.inf
  16.     square=numbers[index]*numbers[index]
  17.     if current_sum+square<=target:
  18.         take=1+fun(index,current_sum+square,numbers,dp,target)
  19.        
  20.     not_take=fun(index-1,current_sum,numbers,dp,target)
  21.     dp[index][current_sum]=min(take,not_take)
  22.     return dp[index][current_sum]
  23.  
  24.  
  25. class Solution:
  26.     def numSquares(self,n):
  27.         r=int(sqrt(n))
  28.         numbers=[i for i in range(1,r+1)]
  29.         dp=[[-1]*(n+1) for _ in range(limit)]
  30.         return fun(r-1,0,numbers,dp,n)
Advertisement
Add Comment
Please, Sign In to add comment