[Naive Approach] Using Recursion - O(2^n) Time and O(n) Space
The idea is to use the property that each element i in the Pascal triangle is equal to the sum of two elements directly above it (i-1 and i), with the base condition that the first and last element of any row will be equal to 1.
C++
// C++ program to Find the nth row in // Pascal’s Triangle using Recursion #include<bits/stdc++.h>usingnamespacestd;// Function which recursively finds the // ith value of nth row.intfindVal(inti,intn){// First and last value of each // row will always be 1.if(i==1||i==n){return1;}// Find the (i-1)th and ith // value of previous row returnfindVal(i-1,n-1)+findVal(i,n-1);}// Function to find the elements // of n'th row in Pascal's Triangle vector<int>nthRowOfPascalTriangle(intn){vector<int>res;for(inti=1;i<=n;i++){intval=findVal(i,n);res.push_back(val);}returnres;}intmain(){intn=4;vector<int>ans=nthRowOfPascalTriangle(n);for(inti=0;i<ans.size();i++){cout<<ans[i]<<" ";}cout<<endl;return0;}
Java
// Java program to Find the nth row in // Pascal’s Triangle using Recursion importjava.util.*;classGfG{// Function which recursively finds the // ith value of nth row.staticintfindVal(inti,intn){// First and last value of each // row will always be 1.if(i==1||i==n){return1;}// Find the (i-1)th and ith // value of previous row returnfindVal(i-1,n-1)+findVal(i,n-1);}// Function to find the elements // of n'th row in Pascal's Triangle staticArrayList<Integer>nthRowOfPascalTriangle(intn){ArrayList<Integer>res=newArrayList<>();for(inti=1;i<=n;i++){intval=findVal(i,n);res.add(val);}returnres;}publicstaticvoidmain(String[]args){intn=4;ArrayList<Integer>ans=nthRowOfPascalTriangle(n);for(inti=0;i<ans.size();i++){System.out.print(ans.get(i)+" ");}System.out.println();}}
Python
# Python program to Find the nth row in # Pascal’s Triangle using Recursion # Function which recursively finds the # ith value of nth row.deffindVal(i,n):# First and last value of each # row will always be 1.ifi==1ori==n:return1# Find the (i-1)th and ith # value of previous row returnfindVal(i-1,n-1)+findVal(i,n-1)# Function to find the elements # of n'th row in Pascal's Triangle defnthRowOfPascalTriangle(n):res=[]foriinrange(1,n+1):val=findVal(i,n)res.append(val)returnresif__name__=="__main__":n=4ans=nthRowOfPascalTriangle(n)foriinrange(len(ans)):print(ans[i],end=" ")print()
C#
// C# program to Find the nth row in // Pascal’s Triangle using Recursion usingSystem;usingSystem.Collections.Generic;classGfG{// Function which recursively finds the // ith value of nth row.staticintfindVal(inti,intn){// First and last value of each // row will always be 1.if(i==1||i==n){return1;}// Find the (i-1)th and ith // value of previous row returnfindVal(i-1,n-1)+findVal(i,n-1);}// Function to find the elements // of n'th row in Pascal's Triangle staticList<int>nthRowOfPascalTriangle(intn){List<int>res=newList<int>();for(inti=1;i<=n;i++){intval=findVal(i,n);res.Add(val);}returnres;}staticvoidMain(string[]args){intn=4;List<int>ans=nthRowOfPascalTriangle(n);for(inti=0;i<ans.Count;i++){Console.Write(ans[i]+" ");}Console.WriteLine();}}
JavaScript
// Function which recursively finds the // ith value of nth row.functionfindVal(i,n){// First and last value of each // row will always be 1.if(i===1||i===n){return1;}// Find the (i-1)th and ith // value of previous row returnfindVal(i-1,n-1)+findVal(i,n-1);}// Function to find the elements // of n'th row in Pascal's Triangle functionnthRowOfPascalTriangle(n){letres=[];for(leti=1;i<=n;i++){letval=findVal(i,n);res.push(val);}returnres;}// Driver codeletn=4;letans=nthRowOfPascalTriangle(n);console.log(ans.join(' '));
Output
1 3 3 1
[Better Approach] Using Recursion Level by Level - O(n^2) Time and O(n) Space
The idea is to recursively find the n'throw by recursively finding the previous row. Then use the previous row to calculate the values of current row.
C++
// C++ program to Find the nth row in // Pascal’s Triangle using Recursion #include<bits/stdc++.h>usingnamespacestd;// Function to find the elements // of n'th row in Pascal's Triangle vector<int>nthRowOfPascalTriangle(intn){vector<int>curr;// 1st element of every row is 1 curr.push_back(1);// Check if the row that has to // be returned is the first row if(n==1){returncurr;}// Generate the previous row vector<int>prev=nthRowOfPascalTriangle(n-1);for(inti=1;i<prev.size();i++){// Generate the elements of the current// row with the help of the previous row intval=prev[i-1]+prev[i];curr.push_back(val);}curr.push_back(1);// Return the row returncurr;}intmain(){intn=4;vector<int>ans=nthRowOfPascalTriangle(n);for(inti=0;i<ans.size();i++){cout<<ans[i]<<" ";}cout<<endl;return0;}
Java
// Java program to Find the nth row in // Pascal’s Triangle using Recursion importjava.util.*;classGfG{// Function to find the elements // of n'th row in Pascal's Triangle staticArrayList<Integer>nthRowOfPascalTriangle(intn){ArrayList<Integer>curr=newArrayList<>();// 1st element of every row is 1 curr.add(1);// Check if the row that has to // be returned is the first row if(n==1){returncurr;}// Generate the previous row ArrayList<Integer>prev=nthRowOfPascalTriangle(n-1);for(inti=1;i<prev.size();i++){// Generate the elements of the current// row with the help of the previous row intval=prev.get(i-1)+prev.get(i);curr.add(val);}curr.add(1);// Return the row returncurr;}publicstaticvoidmain(String[]args){intn=4;ArrayList<Integer>ans=nthRowOfPascalTriangle(n);for(inti=0;i<ans.size();i++){System.out.print(ans.get(i)+" ");}System.out.println();}}
Python
# Python program to Find the nth row in # Pascal’s Triangle using Recursion # Function to find the elements # of n'th row in Pascal's Triangle defnthRowOfPascalTriangle(n):curr=[]# 1st element of every row is 1 curr.append(1)# Check if the row that has to # be returned is the first row ifn==1:returncurr# Generate the previous row prev=nthRowOfPascalTriangle(n-1)foriinrange(1,len(prev)):# Generate the elements of the current# row with the help of the previous row val=prev[i-1]+prev[i]curr.append(val)curr.append(1)# Return the row returncurrif__name__=="__main__":n=4ans=nthRowOfPascalTriangle(n)forvalinans:print(val,end=" ")print()
C#
// C# program to Find the nth row in // Pascal’s Triangle using Recursion usingSystem;usingSystem.Collections.Generic;classGfG{// Function to find the elements // of n'th row in Pascal's Triangle staticList<int>nthRowOfPascalTriangle(intn){List<int>curr=newList<int>();// 1st element of every row is 1 curr.Add(1);// Check if the row that has to // be returned is the first row if(n==1){returncurr;}// Generate the previous row List<int>prev=nthRowOfPascalTriangle(n-1);for(inti=1;i<prev.Count;i++){// Generate the elements of the current// row with the help of the previous row intval=prev[i-1]+prev[i];curr.Add(val);}curr.Add(1);// Return the row returncurr;}staticvoidMain(string[]args){intn=4;List<int>ans=nthRowOfPascalTriangle(n);for(inti=0;i<ans.Count;i++){Console.Write(ans[i]+" ");}Console.WriteLine();}}
JavaScript
// JavaScript program to Find the nth row in // Pascal’s Triangle using Recursion // Function to find the elements // of n'th row in Pascal's Triangle functionnthRowOfPascalTriangle(n){letcurr=[];// 1st element of every row is 1 curr.push(1);// Check if the row that has to // be returned is the first row if(n===1){returncurr;}// Generate the previous row letprev=nthRowOfPascalTriangle(n-1);for(leti=1;i<prev.length;i++){// Generate the elements of the current// row with the help of the previous row letval=prev[i-1]+prev[i];curr.push(val);}curr.push(1);// Return the row returncurr;}letn=4;letans=nthRowOfPascalTriangle(n);console.log(ans.join(' '));
Output
1 3 3 1
[Expected Approach] Using Combinatorics - O(n) Time and O(n) Space
The idea is to use the mathematical relationship between consecutive elements in a Pascal's Triangle row, rather than computing the entire triangle. Since the nth row consists of binomial coefficients nC0, nC1, ..., nCn, we can calculate each element directly from the previous one using the formula: nCr = (nCr-1 * (n-r+1))/r. This approach starts with nC0 = 1 and efficiently computes each subsequent value
Note: This approach uses 0-based indexing because the mathematical formula used for calculating binomial coefficients aligns with 0-based indexing.
Step by step approach:
Start with first element of the row as 1 (nC0 = 1).
For each subsequent element, use the formula nCr = (nCr-1 * (n-r+1))/r.
Build the row progressively by calculating one element at a time.
Adjust for 1-based indexing by decrementing n before calculations.
How is the formula calculated?
nCi = n! / (i! * (n-i)!) : ith element of nth row
nCi+1 = n! / ((i+1)! * (n-(i+1))!) : (i+1)th element of nth row
Simplifying: nCi+1 = nCi * (n-i) / (i+1) - This lets us compute each element from the previous one
C++
// C++ program to Find the nth row in Pascal’s// Triangle using efficient approach #include<bits/stdc++.h>usingnamespacestd;// Function to find the elements // of n'th row in Pascal's Triangle vector<int>nthRowOfPascalTriangle(intn){// To follow 0 based indexing, decrement n n--;vector<int>res;// nC0 = 1intprev=1;res.push_back(prev);for(inti=1;i<=n;i++){// nCr = (nCr-1 * (n - r + 1))/r intcurr=(prev*(n-i+1))/i;res.push_back(curr);prev=curr;}returnres;}intmain(){intn=4;vector<int>ans=nthRowOfPascalTriangle(n);for(inti=0;i<ans.size();i++){cout<<ans[i]<<" ";}cout<<endl;return0;}
Java
// Java program to Find the nth row in Pascal’s// Triangle using efficient approach importjava.util.*;classGfG{// Function to find the elements // of n'th row in Pascal's Triangle staticArrayList<Integer>nthRowOfPascalTriangle(intn){// To follow 0 based indexing, decrement n n--;ArrayList<Integer>res=newArrayList<>();// nC0 = 1intprev=1;res.add(prev);for(inti=1;i<=n;i++){// nCr = (nCr-1 * (n - r + 1))/r intcurr=(prev*(n-i+1))/i;res.add(curr);prev=curr;}returnres;}publicstaticvoidmain(String[]args){intn=4;ArrayList<Integer>ans=nthRowOfPascalTriangle(n);for(inti=0;i<ans.size();i++){System.out.print(ans.get(i)+" ");}System.out.println();}}
Python
# Python program to Find the nth row in Pascal’s# Triangle using efficient approach # Function to find the elements # of n'th row in Pascal's Triangle defnthRowOfPascalTriangle(n):# To follow 0 based indexing, decrement n n-=1res=[]# nC0 = 1prev=1res.append(prev)foriinrange(1,n+1):# nCr = (nCr-1 * (n - r + 1))/r curr=(prev*(n-i+1))//ires.append(curr)prev=currreturnresif__name__=="__main__":n=4ans=nthRowOfPascalTriangle(n)forvalinans:print(val,end=" ")print()
C#
// C# program to Find the nth row in Pascal’s// Triangle using efficient approach usingSystem;usingSystem.Collections.Generic;classGfG{// Function to find the elements // of n'th row in Pascal's Triangle staticList<int>nthRowOfPascalTriangle(intn){// To follow 0 based indexing, decrement n n--;List<int>res=newList<int>();// nC0 = 1intprev=1;res.Add(prev);for(inti=1;i<=n;i++){// nCr = (nCr-1 * (n - r + 1))/r intcurr=(prev*(n-i+1))/i;res.Add(curr);prev=curr;}returnres;}staticvoidMain(string[]args){intn=4;List<int>ans=nthRowOfPascalTriangle(n);for(inti=0;i<ans.Count;i++){Console.Write(ans[i]+" ");}Console.WriteLine();}}
JavaScript
// Function to find the elements // of n'th row in Pascal's Triangle functionnthRowOfPascalTriangle(n){// To follow 0 based indexing, decrement n n--;letres=[];// nC0 = 1letprev=1;res.push(prev);for(leti=1;i<=n;i++){// nCr = (nCr-1 * (n - r + 1))/r letcurr=Math.floor((prev*(n-i+1))/i);res.push(curr);prev=curr;}returnres;}letn=4;letans=nthRowOfPascalTriangle(n);console.log(ans.join(' '));