Advertisement
Iam_Sandeep

Coin change varient,Perfect Sqaures add to sum 2d dp to 1d dp

Jul 10th, 2022
1,336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. '''
  2. Try to make 1D dp possible
  3.  
  4. This gave TLE. Since I used 2d dp in python.
  5. Both are kind of coin change varient either add or dont add type. Whats the difference. WHy method 2 gave TLE why other didnot?
  6. What diff between method 1 and method 2 varient.
  7. Method 1:can only give min no of denominations
  8. Method 2:can give min no of denominations and also tells which are the denominations that adds up to given sum value
  9. '''
  10. class Solution:
  11.     def numSquares(self, n: int) -> int:
  12.         q=[]
  13.         for i in range(1,int(n**0.5)+1):
  14.             if i*i<=n:
  15.                 q.append(i*i)
  16.             else:
  17.                 break
  18.         @cache
  19.         def find(s):
  20.             if s==0:return 0
  21.             if s<0:return 0
  22.             ans=float('inf')
  23.             for sq in q:
  24.                 if s-sq>=0:
  25.                     ans=min(ans,1+find(s-sq))
  26.             return ans
  27.         return find(n)
  28.  
  29. class Solution:
  30.     def numSquares(self, n: int) -> int:
  31.         q=[]
  32.         for i in range(1,n+1):
  33.             if i*i<=n:
  34.                 q.append(i*i)
  35.             else:
  36.                 break
  37.         #print(q)
  38.         @cache
  39.         def find(x,i):
  40.            
  41.             if x==0:
  42.                 return 0
  43.             if x<0 or  i>=len(q) or q[i]>x :
  44.                 return float('inf')
  45.             else:
  46.                 return min(1+find(x-q[i],i),find(x,i+1))
  47.         return find(n,0)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement