### 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.
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 getRow(int A) { ArrayList> res = new ArrayList>(); for(int i=0;i<=A;i++){ ArrayList tmp = new ArrayList(); 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<>();
for(int i = 1; i<=rowIndex; i++){
long tmp = ((long)ans.get(i-1)*(rowIndex-(i-1))/(i));
}
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++){
}
return ans;
}
}
```

Other Posts You May Like