首页 > 其他 > 详细

Leetcode[118]-Pascal's Triangle

时间:2015-06-09 10:04:31      阅读:261      评论:0      收藏:0      [点我收藏+]

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

分析:

  • 第j=0列全为1,第j==i列时,都为1
  • 其它列
    • a[2][1] = a[1][0]+a[1][1]
    • a[3][1] = a[2][0]+a[2][1]
    • a[3][2] = a[2][1]+a[2][2]
    • ……
    • 推算得出
    • ……
    • a[i][j] = a[i-1][j-1]+a[i-1][j]

代码(c++):

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector <vector<int> > vec(numRows);
        for(int i = 0; i < numRows; i++) {
            vec[i].resize(i+1);
            for(int j = 0; j <= i ; j++){
                if(j==i || j==0)
                    vec[i][j] = 1;
                else{
                    vec[i][j] = vec[i-1][j-1] + vec[i-1][j];
                }
            }
        }
        return vec;
    }
};

Leetcode[118]-Pascal's Triangle

原文:http://blog.csdn.net/dream_angel_z/article/details/46417769

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!