leetcode解题报告(24):Pascal's TriangleII

描述

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,

Return [1,3,3,1].

分析

先构造了一个杨辉三角,然后返回这个杨辉三角的最后一组值,没超时就万事大吉了...

感觉可以用递归写,但是嫌麻烦,放弃了。

代码如下:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int>ele; //store elements of current line
        vector<vector<int>>ret; //store all the lines and as a return variable 
        if(rowIndex < 0)return ele;     //return an empty vector if rowIndex == 0
        int j = 0;  //initialize j
        for(int i = 0; i <= rowIndex; ++i){  
            ele.push_back(1);   //push 1 before do any operators in a line
            if(i >= 1){ 
                j = 1;
                while(j < i){
                    ele.push_back(ret[i - 1][j - 1] + ret[i - 1][j]);
                    ++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[rowIndex];
    }
};
posted @ 2017-05-17 14:31  larryking  阅读(143)  评论(0编辑  收藏  举报