Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //To print the full pascal traingle TC. O(n^2)
- class Solution {
- public:
- vector<vector<int>> generate(int n) {
- vector <vector <int>> arr(n);
- for(int i=0;i<n;i++){
- arr[i].resize(i+1); //making the row of required size
- arr[i][0]=arr[i][i]=1; //making first and last element always 1
- for(int j=1;j<i;j++){ //taking care of middle elements
- arr[i][j]=arr[i-1][j-1]+arr[i-1][j];
- }
- }
- return arr;
- }
- };
- //To print a row of pascal's traingle
- /*
- Logic:
- If you observe then you will find that the nth row elements are :
- nc0,nc1,nc2,nc3,nc4,nc5....ncn(where n is 1 based indexing)
- so we can calculate nc0,nc1,nc2...one by one.
- Improvisation:
- NCr = (NC(r-1) * (N - r + 1)) / r where 1 ≤ r ≤ N
- so if NC0=1 keep it in prev variable
- so NC1=1*(N-1+1) and so on.
- #include <bits/stdc++.h>
- using namespace std;
- int main()
- {
- int N;cin>>N;
- int prev = 1; // nC0 = 1
- cout << prev;
- for (int i = 1; i <= N; i++) {
- // nCr = (nCr-1 * (n - r + 1))/r
- int curr = (prev * (N - i + 1)) / i;
- cout << ", " << curr; //printing ith element of row
- prev = curr;
- return 0;
- }
- */
- /*
- Same above approach if row needed considering large number as the modulo of 10^9+7
- */
- ll val=pow(10,9)+7;
- ll gcdExtended(ll a, ll b, ll *x, ll *y)
- {
- // Base Case
- if (a == 0)
- {
- *x = 0, *y = 1;
- return b;
- }
- ll x1, y1; // To store results of recursive call
- ll gcd = gcdExtended(b%a, a, &x1, &y1);
- // Update x and y using results of recursive
- // call
- *x = y1 - (b/a) * x1;
- *y = x1;
- return gcd;
- }
- ll modInverse(ll b, ll m)
- {
- ll x, y; // used in extended GCD algorithm
- ll g = gcdExtended(b, m, &x, &y);
- // Return -1 if b and m are not co-prime
- if (g != 1)
- return -1;
- // m is added to handle negative x
- return (x%m + m) % m;
- }
- ll modDivide(ll a, ll b, ll m){
- a = a % m;
- ll inv = modInverse(b, m);
- return ((inv * a) % m);
- }
- class Solution{
- public:
- vector<ll> nthRowOfPascalTriangle(int n) {
- n--;
- ll prev = 1;
- vector <ll> res;
- res.push_back(1);
- for (int i = 1; i <= n; i++) {
- // nCr = (nCr-1 * (n - r + 1))/r
- ll curr = (prev * (n - i + 1))%val; //This is NC(r-1)*(n-i+1)
- curr=modDivide(curr,i,val); //This is curr/i
- res.push_back(curr);
- prev = curr;
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement