Kth Row of Pascal's Triangle - The Coding Shala

Home >> Interview Questions >> Kth row of pascal's triangle

Kth Row of Pascal's Triangle Solution Java

Given an index k, return the kth row of Pascal’s triangle.
Kth Row of Pascal's Triangle - The Coding Shala
Example:
Input : k = 3

Return : [1,3,3,1]

Java Solution of Kth Row of Pascal's Triangle

One simple method to get the Kth row of Pascal's Triangle is to generate Pascal Triangle till Kth row and return the last row. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class Solution {
    public ArrayList<Integer> getRow(int A) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        for(int i=0;i<=A;i++){
            ArrayList<Integer> tmp = new ArrayList<Integer>();
            for(int j=0;j<=i;j++){
                if(j==i || j==0) tmp.add(1);
                else
                tmp.add(res.get(i-1).get(j) + res.get(i-1).get(j-1));
            }
            res.add(tmp);
        }
        return res.get(A);
    }
}

Approach 2:

We can directly generate Kth row of Pascal's triange using below formula: 

P[k, i] = (P[k,i-1]*(k-i+1))/i

Java 

class Solution {
    public List<Integer> getRow(int rowIndex) {
       List<Integer> ans = new ArrayList<>();
        ans.add(1);
        for(int i = 1; i<=rowIndex; i++){
            long tmp = ((long)ans.get(i-1)*(rowIndex-(i-1))/(i));
            ans.add((int)tmp);
        }
        return ans;
    }
}

Approach 3:
Using Recursion.
Java Program: 

class Solution {
    public List<Integer> getRow(int rowIndex) {
       if(rowIndex == 0) return Arrays.asList(1);
        List<Integer> prev = getRow(rowIndex-1);
        List<Integer> ans = new ArrayList<Integer>();
        for(int i=0; i<prev.size();i++){
            if(i==0) ans.add(1);
            if(i>0) ans.add(prev.get(i-1)+prev.get(i));
            if(i == prev.size()-1) ans.add(1);
        }
        return ans;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Program to Convert Decimal to Binary - The Coding Shala