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

Pascal's Triangle - Array - Easy - LeetCode

1 min read 109 words
1 min read
ShareWhatsAppPost on X
  • 1Pascal's triangle is generated by summing the two numbers directly above each position in the triangle.
  • 2The function generates the first numRows of Pascal's triangle as a list of lists.
  • 3The implementation handles edge cases for numRows values of 0, 1, and 2.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Pascal's triangle is generated by summing the two numbers directly above each position in the triangle."

Pascal's Triangle - Array - Easy - LeetCode

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

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

Example:

Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]

public class Solution {
 public IList<IList<int>> Generate(int numRows) {
 var result = new List<IList<int>>();
 if(numRows == 0){
 return result;
 }
 var list = new List<int>();
 list.Add(1);
 result.Add(list);
 
 if(numRows == 1){
 return result;
 }
 
 list = new List<int>();
 list.Add(1);
 list.Add(1);
 result.Add(list);
 if(numRows == 2){
 return result;
 }
 
 for(int i=2;i<numRows;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;
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

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

Part of AskGif Blog · coding

You might also like