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即可。
1 class Solution { 2 public: 3 vector<vector<int> > generate(int numRows) 4 { 5 vector<vector<int>> res; 6 7 for(int i=0;i<numRows;++i) 8 { 9 vector<int> temp; 10 11 for(int j=0;j<i+1;++j) 12 { 13 if(j==0||j==i) 14 temp.push_back(1); 15 else 16 { 17 int tep=res[i-1][j-1]+res[i-1][j]; 18 temp.push_back(tep); 19 } 20 } 21 res.push_back(temp); 22 } 23 return res; 24 } 25 };
个人想法是:先整体后局部,整体根据局部调整。