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]
]
class Solution{
public:
	vector<vector<int> > generate(int numRows) {

		vector<vector<int> > re(numRows);
		for (int i = 0; i < numRows; ++i)
		{
			vector<int> temp(i+1);
			temp[0] = 1;
			for (int j = 1; j < i; ++j)
			{
				temp[j] = re[i - 1][j] + re[i - 1][j - 1];
			}
			temp[i] = 1;
			re[i] = temp;
		}
		return re;
	}

};
题目给定的例子程序看着不明显,将其写成矩阵形式更容易发现规律,递归式 d[i,j] = d[i - 1, j] + d[i-1, j-1]。i为行,j为列。

你可能感兴趣的:(LeetCode,pascal)