imashutosh51

Pascal's triangle

Jul 22nd, 2022 (edited)
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. //To print the full pascal traingle TC. O(n^2)
  2. class Solution:
  3.     def generate(self, n: int):
  4.         arr = [[] for _ in range(n)]
  5.  
  6.         for i in range(n):
  7.             arr[i] = [0] * (i + 1)          # make row of required size
  8.             arr[i][0] = arr[i][i] = 1       # first and last element are always 1
  9.  
  10.             for j in range(1, i):           # fill middle elements
  11.                 arr[i][j] = arr[i-1][j-1] + arr[i-1][j]
  12.  
  13.         return arr
  14.  
  15.  
  16. //To print a row of pascal's traingle
  17. /*
  18. Logic:
  19. If you observe then you will find that the nth row elements are :
  20. nc0,nc1,nc2,nc3,nc4,nc5....ncn(where n is 1 based indexing)
  21. so we can calculate nc0,nc1,nc2...one by one.
  22.  
  23. Improvisation:
  24. NCr = (NC(r-1) * (N - r + 1)) / r where 1 ≤ r ≤ N
  25. so if NC0=1 keep it in prev variable
  26. so NC1=1*(N-1+1) and so on.
  27.  
  28. class Solution:
  29.    def generate(self, sz: int) -> List[List[int]]:
  30.        ans=[]
  31.        for i in range(sz):
  32.            temp=[1]
  33.            n=i
  34.            for j in range(1,n+1):
  35.                val=(temp[-1]*(n-j+1))//j
  36.                temp.append(val)
  37.            ans.append(temp)
  38.        return ans
  39.  
  40. */
  41.  
  42. /*
  43. Same above approach if row needed considering large number as the modulo of 10^9+7
  44. */
  45. MOD = 10**9 + 7
  46.  
  47. def gcd_extended(a, b):
  48.    # Base case
  49.    if a == 0:
  50.        return b, 0, 1
  51.  
  52.    gcd, x1, y1 = gcd_extended(b % a, a)
  53.  
  54.    # Update x and y
  55.    x = y1 - (b // a) * x1
  56.    y = x1
  57.  
  58.    return gcd, x, y
  59.  
  60.  
  61. def mod_inverse(b, m):
  62.    gcd, x, _ = gcd_extended(b, m)
  63.  
  64.    # If inverse doesn't exist
  65.     if gcd != 1:
  66.         return -1
  67.  
  68.     return (x % m + m) % m
  69.  
  70.  
  71. def mod_divide(a, b, m):
  72.     a %= m
  73.     inv = mod_inverse(b, m)
  74.     return (a * inv) % m
  75.  
  76.  
  77. class Solution:
  78.     def nthRowOfPascalTriangle(self, n: int):
  79.         n -= 1  # convert to 0-based
  80.         prev = 1
  81.         res = [1]
  82.  
  83.         for i in range(1, n + 1):
  84.             # nCr = nC(r-1) * (n - r + 1) / r
  85.             curr = (prev * (n - i + 1)) % MOD
  86.             curr = mod_divide(curr, i, MOD)
  87.             res.append(curr)
  88.             prev = curr
  89.  
  90.         return res
  91.  
Advertisement
Add Comment
Please, Sign In to add comment