Blogs Hub

Pascal's Triangle II - Array - Easy - LeetCode - MiniTV

Pascal's Triangle II - Array - Easy - LeetCode - मिनी टीवी

Given an integer rowIndex, return the rowIndexth row of Pascal's triangle.

Notice that the row index starts from 0.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

 

Example 1:

Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:

Input: rowIndex = 0
Output: [1]
Example 3:

Input: rowIndex = 1
Output: [1,1]
 

Constraints:

0 <= rowIndex <= 40

public class Solution {
    public IList<int> GetRow(int rowIndex) {
        var result = new List<IList<int>>();        
        var list = new List<int>();
        list.Add(1);
        result.Add(list);
        
        if(rowIndex == 0){
            return list;
        }
        
        list = new List<int>();
        list.Add(1);
        list.Add(1);
        result.Add(list);
        if(rowIndex == 1){
            return list;
        }
        
        for(int i=2;i<=rowIndex;i++){
            list = new List<int>();
            for(int j=0;j<=result[i-1].Count;j++){
                if(j==0){
                    list.Add(result[i-1][0]);
                }
                else if(j==result[i-1].Count){
                    list.Add(result[i-1][result[i-1].Count-1]);
                }
                else{
                    list.Add(result[i-1][j-1]+result[i-1][j]);
                }
            }
            result.Add(list);
        }
        
        return result[rowIndex];
    }
}