Arithmetic Triangle

Arithmetic Triangle

Difficulty: Easy

Given an integer numRows, return the first numRows of Arithmetic's triangle.

In Arithmetic's triangle, each number is the sum of the two numbers directly above it as shown:






Solution: 
Java

class Solution {
    List<List<Integer>> list;
    public List<List<Integer>> generate(int numRows) {
        list=new ArrayList<>();
        if(numRows==0)
            return list;
        list.add(new ArrayList<Integer>(Arrays.asList(1)));
        for(int i=1;i<numRows;i++){
            List<Integer> l=new ArrayList<Integer>();
            List<Integer> prev=list.get(i-1);
            for(int j=0;j<=i;j++){
                if(i==0||j==0||i==1||i==j){
                    l.add(1);
                    continue;
                }
                l.add(prev.get(j)+prev.get(j-1));
            }
            list.add(l);
        }
        return list;
    }
}

Contributed By: Mohammed Raeesul Irfan CSE

Python

class Solution:
   def generate(self, numRows: int) -> List[List[int]]:
        if numRows == 0:
            return []
        if numRows == 1:
            return [[1]]
        res = [[1]*i for i in range(1,numRows+1)]    
        for i in range(1,numRows):
            for j in range(1,i):
                res[i][j] = res[i-1][j-1]+res[i-1][j]
        print(res)
        return res

Comments

  1. Be free to comment your thoughts hear

    ReplyDelete
  2. Another pythonic solution :
    `
    n = 5
    a = []
    for row in range(1, n+1):
    sa = []
    c = 1
    for i in range(1, row+1):
    sa.append(c)
    c = c * (row-i) // i
    a.append(sa)
    print(a)
    `

    ReplyDelete

Post a Comment