[Leetcode] 118. Pascal's Triangle
Posted seako
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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
以上是关于[Leetcode] 118. Pascal's Triangle的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode118:Pascal's Triangle
[leetcode-118-Pascal's Triangle]
leetcode 118 Pascal's Triangle ----- java
[LeetCode] NO. 118 Pascal's Triangle