Pascal's Triangle II - Array - Easy - LeetCode
💻 coding

Pascal's Triangle II - Array - Easy - LeetCode

1 min read 142 words
1 min read
ShareWhatsAppPost on X
  • 1Pascal's triangle is constructed such that each number is the sum of the two numbers directly above it.
  • 2The function GetRow returns the rowIndexth row of Pascal's triangle, starting from index 0.
  • 3An optimization challenge is to achieve this with O(k) extra space complexity.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Pascal's triangle is constructed such that each number is the sum of the two numbers directly above it."

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];
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 25 September 2020 · 1 min read · 142 words

Part of AskGif Blog · coding

You might also like