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~n递增
行:一行的第一个和最后一个元素都为1,中间的元素为上一行元素当前列和前一列的和。
Python语言
主要使用list列表,用到list常用操作list.append(x)添加一个元素.
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
#定义一个二维数组并初始化
a = []
for row in range(0,numRows):
temp = []
print "row=",row
for col in range(0,row+1):
if col==0 or col==row:
temp.append(1)
else:
temp.append(a[row-1][col-1]+a[row-1][col])
a.append(temp)
return a
C++语言
主要用到c++中的容器vector,使用push_back()方法添加元素.
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>>a;
for(int i=0; i<numRows; i++)
{
vector<int>temp;
for(int j=0; j<=i; j++)
{
if(j==0||j==i)
temp.push_back(1);
else
temp.push_back(a[i-1][j-1]+a[i-1][j]);
}
a.push_back(temp);
}
return a;
}
};