代码改变世界

[LeetCode]Pascal's Triangle

2014-03-15 23:23  庸男勿扰  阅读(122)  评论(0编辑  收藏  举报

原题链接:http://oj.leetcode.com/problems/pascals-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]
]

题解:

  两端为1,中间为v[i][j] = v[i-1][j-1]+v[i-1][j];

 1 class Solution {
 2 public:
 3     vector<vector<int> > generate(int numRows) {
 4         vector <vector<int>> v(numRows); 
 5         for(int i=0;i<numRows;i++)
 6             v[i].resize(i+1);
 7         
 8         for(int i=0; i<numRows; i++){
 9             for(int j=0; j<i+1; j++){
10                 if(j==0 || j==i)
11                     v[i][j] = 1;
12                 else
13                     v[i][j] = v[i-1][j-1]+v[i-1][j];
14             }
15         }
16         
17         return v;
18     }
19 };
View Code