[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] ]
杨辉三角形,又称贾宪三角形、帕斯卡三角形、海亚姆三角形、巴斯卡三角形,是二项式系数在的一种写法,形似三角形,在中国首现于南宋杨辉的《详解九章算术》得名,书中杨辉说明是引自贾宪的《释锁算术》,故又名贾宪三角形。前 9 行写出来如下:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1
杨辉三角形第 层(顶层称第 0 层,第 1 行,第
层即第
行,此处
为包含 0 在内的自然数)正好对应于二项式
展开的系数。例如第二层 1 2 1 是幂指数为 2 的二项式
展开形式
的系数。
解法:每一行的首个和结尾一个数字都是1,从第三行开始,中间的每个数字都是上一行的左右两个数字之和。
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class Solution { public List<List<Integer>> generate( int numRows) { List<List<Integer>> res = new ArrayList<>(); if (numRows <= 0 ) return res; List<Integer> list = new ArrayList<>(); for ( int i = 1 ; i <= numRows; i++) { list.add( 1 ); for ( int j = list.size() - 2 ; j > 0 ; j--) { list.set(j, list.get(j) + list.get(j - 1 )); } res.add( new ArrayList<>(list)); } return res; } } |
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class Solution { public List<List<Integer>> generate( int numRows) { List<List<Integer>> res = new ArrayList<>(); if (numRows <= 0 ) return res; ArrayList<Integer> list = new ArrayList<>(); list.add( 1 ); res.add(list); for ( int i = 1 ; i < numRows; i++) { ArrayList<Integer> temp = new ArrayList<>(); temp.add( 1 ); for ( int j = 1 ; j < res.get(i - 1 ).size(); j++) temp.add(res.get(i - 1 ).get(j) + res.get(i - 1 ).get(j - 1 )); temp.add( 1 ); res.add(temp); } return res; } } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 | class Solution: # @return a list of lists of integers def generate( self , numRows): result = [] for i in xrange (numRows): result.append([]) for j in xrange (i + 1 ): if j in ( 0 , i): result[i].append( 1 ) else : result[i].append(result[i - 1 ][j - 1 ] + result[i - 1 ][j]) return result |
Python:
1 2 3 4 5 6 7 | class Solution: def generate( self , numRows): if not numRows: return [] res = [[ 1 ]] for i in range ( 1 , numRows): res + = [ map ( lambda x, y: x + y, res[ - 1 ] + [ 0 ], [ 0 ] + res[ - 1 ])] return res[:numRows] |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Solution { public : vector<vector< int > > generate( int numRows) { vector<vector< int > > res; if (numRows <= 0) return res; res.assign(numRows, vector< int >(1)); for ( int i = 0; i < numRows; ++i) { res[i][0] = 1; if (i == 0) continue ; for ( int j = 1; j < i; ++j) { res[i].push_back(res[i-1][j] + res[i-1][j-1]); } res[i].push_back(1); } return res; } }; |
类似题目:
[LeetCode] 119. Pascal's Triangle II 杨辉三角 II
All LeetCode Questions List 题目汇总
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步