leetcode解题报告(23):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]
]

分析

其实就是杨辉三角,以前用队列写过。

为了和numRows相匹配,以变量i代表当前的行数,那么i-1才是当前行的下标。以j代表当前行的第i个元素(这个j是从下标1开始的)。

代码如下:

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<int>ele; //store elements of current line
        vector<vector<int>>ret; //store all the lines and as a return variable 
        if(numRows == 0)return ret;     //return an empty vector if numRows == 0
        int j = 0;  //initialize j
        for(int i = 1; i <= numRows; ++i){  //note: i begins from 1,means the first line
            ele.push_back(1);   //push 1 before do any operators in a line
            if(i >= 2){ 
                j = 2;
                while(j < i){
                    //because i starts with 1,so i - 1 is current line,while i - 2 is the line before current
                    //so as to j
                    ele.push_back(ret[i - 2][j - 2] + ret[i - 2][j - 1]);
                    ++j;    
                }
                ele.push_back(1);   //the last number in a line is also 1 
            }
            ret.push_back(ele);
            ele.clear();    //each time we finish a line,clear this vector
        }
        return ret;
    }
};
posted @ 2017-05-17 14:30  larryking  阅读(118)  评论(0编辑  收藏  举报