1.题目
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]
]
按照上述规律生成结果。
2.分析
第一种解法:
按照规律 第i行 i个数字 首尾是1 其他 row[i][j]=row[i-1][j-1]+row[i-1][j];
第二种解法:
移位求和,例如
0 1 3 3 1
1 3 3 1 0
1 4 6 4 1
3.代码
第一种解法
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ans;
if (numRows == 0)
return ans;
ans.push_back(vector<int>{1});
for (int i = 1; i < numRows; i++)
{
vector<int> row;
row.push_back(1);
for (int j = 1; j < i; j++)
{
row.push_back(ans[i - 1][j - 1] + ans[i - 1][j]);
}
row.push_back(1);
ans.push_back(row);
}
return ans;
}
第二种:
python
class Solution(object):
def generate(self, numRows):
ans=[[1]]
for i in range(1,numRows):
ans.append(map(lambda x,y:x+y,[0]+ans[i-1],ans[i-1]+[0]))
return ans[:numRows]