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
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
Comments
Post a Comment