Pascal Triangle - The Coding Shala

Home >> Interview Questions >> Pascal Triangle

Pascal Triangle Java Solution

Given numRows, generate the first numRows of Pascal’s triangle.
Pascal’s triangle: To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1.
Pascal Triangle Java Program - The Coding Shala
Example:
Given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

Solution: (Java)

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



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

LeetCode - Crawler Log Folder Solution - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

New Year Chaos Solution - The Coding Shala

Java Program to Find LCM of Two Numbers - The Coding Shala