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

Leetcode[118]-Pascal's Triangle

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

标签:generate   triangle   return   pascal   分析   

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

标签:generate   triangle   return   pascal   分析   

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

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