Fork me on GitHub

【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]
]

提示:

此题要求计算出给定行数的杨辉三角。只要摸清规律就并不难。

代码:

class Solution {
public:
    vector<vector<int> > generate(int numRows) {
        vector<vector<int>> r(numRows);
        for (int i = 0; i < numRows; i++) {
            // 设置该行的元素个数
            r[i].resize(i + 1);
            // 该行的首尾设置成1
            r[i][0] = r[i][i] = 1;
            // 计算该行中间的元素
            for (int j = 1; j < i; j++)
                r[i][j] = r[i - 1][j - 1] + r[i - 1][j];
        }
        return r;
    }
};
posted @ 2015-09-02 09:31  __Neo  阅读(143)  评论(0编辑  收藏  举报