码迷,mamicode.com
首页 > 其他好文 > 详细

Pascal's Triangle -- leetcode

时间:2015-05-17 15:18:43      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:pascal   triangle   leetcode   

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。

其他列为上一行的当前列和前一列之和。

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> ans(numRows);
        for (int i=0; i<numRows; i++) {
            for (int j=0; j<=i; j++) {
                ans[i].push_back(j!=0 && j!=i ? ans[i-1][j] + ans[i-1][j-1] : 1);
            }
        }
        return ans;
    }
};


Pascal's Triangle -- leetcode

标签:pascal   triangle   leetcode   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45788627

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!