[Leetcode] 118. Pascal's Triangle

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

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

 

python3

 1 class Solution:
 2     def generate(self, numRows: int) -> List[List[int]]:
 3         result = []
 4         for i in range(1,numRows + 1):
 5             if i == 1:
 6                 result.append([1])
 7                 continue
 8             temp = []
 9             for j in range(1,i + 1):
10                 if j == 1 or j == i:
11                     temp.append(1)
12                     continue
13                 temp.append(result[i - 1 - 1][j - 1 - 1] + result[i - 1 - 1][j - 1])
14             result.append(temp)
15         return result

 



posted on 2019-07-14 23:37  seako  阅读(133)  评论(0编辑  收藏  举报