Program to generate Pascal’s Triangle
Pascal triangle : It is one of the pattern question which is frequently asked in several interviews. So let's see this today.
Pascal triangle is one of the triangle of which elements are the sum of its above two elements.
So you need to start thinking about its approach that how you can solve it. And don't jump to the code directly without solving by yourself. Its my humble request.
Now, assume that you will have to return a list of list of elements as pascal triangle.
Side of triangle : Every time we need to add 1 at the start and at the end except first time (because there is only 1 at the top.
Inner triangle (Inner loop) : we need to start from 1st index and should run it upto the outerindex and inside this inner loop we need to extract the above row of triangle from list of lists into a list. And then we will perform the operation on that extracted list.
code in Java :
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list=new ArrayList<>();
for(int i=0;i<numRows;i++)
{
ArrayList<Integer> l=new ArrayList<>();
l.add(1);
for(int j=1;j<i;j++)
{
List<Integer> l2=list.get(i-1);
l.add(l2.get(j-1)+l2.get(j));
}
if(i>0) l.add(1);
list.add(l);
}
return list;
}
}


Comments
Post a Comment