Leetcode 118: Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

 

 1 public class Solution {
 2     public IList<IList<int>> Generate(int numRows) {
 3         var result = new List<IList<int>>();
 4         
 5         if (numRows == 0) return result;
 6         
 7         result.Add(new List<int>(){1});
 8         
 9         for (int i = 2; i <= numRows; i++)
10         {
11             var list = new List<int>();
12             var last = result[result.Count - 1];
13             
14             for (int j = 0; j < i; j++)
15             {
16                 if (j == 0 || j == i - 1)
17                 {
18                     list.Add(1);
19                 }
20                 else
21                 {
22                     list.Add(last[j - 1] + last[j]);
23                 }
24             }
25             
26             result.Add(list);
27         }
28         
29         return result;
30     }
31 }

 

 

 
 
posted @ 2017-11-20 09:12  逸朵  阅读(116)  评论(0)    收藏  举报