letecode [119] - Pascal's Triangle II

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]

 

题目大意:

  输出第k行杨辉三角表示,行下标从0开始。

理  解 :

  根据前一行的值求当前行的值。  

  方法一:动态规划。但每次需要将上次计算的行值赋值给lastRow再求CurRow.

  方法二:递归。重复计算前面行的值。

  方法三。参考其他人的方法,双层循环,外层控制行数,内层在上一行的基础上计算当前行值(从后往前)。每行以1结尾!且注意边界值。

代 码 C++:

  方法一:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> curRow(rowIndex+1);
        vector<int> lastRow;
        curRow[0] = 1;
        curRow[rowIndex] = 1;
        int i=1;
        while(i<=rowIndex){
            lastRow.resize(i);
            for(int j=0;j<i;++j)
                lastRow[j] = curRow[j];
            curRow[0] = 1;
            curRow[i] = 1;
            for(int k=1;k<i;++k){
                curRow[k] = lastRow[k-1] + lastRow[k];
            }
            ++i;
        }
        return curRow;
    }
};

  方法二:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> curRow(rowIndex+1);
        vector<int> lastRow;
        curRow[0] = 1;
        if(rowIndex==0) return curRow;
        curRow[rowIndex] = 1;
        lastRow = getRow(rowIndex-1);
        for(int i=1;i<rowIndex;++i){
            curRow[i] = lastRow[i-1] + lastRow[i];
        }
        return curRow;
    }
};

  方法三:

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> t;
        for(int i=0;i < rowIndex + 1;++i){
            t.push_back(1);
            for(int j=i-1;j>0;--j) t[j]+=t[j-1];
        }
        return t;
    }
};

运行结果:

  方法一:执行用时 : 8 ms  内存消耗 : 8.7 M

  方法二:执行用时 : 4 ms  内存消耗 : 9 M

  方法三:执行用时 : 0 ms  内存消耗 : 8.3 M

posted @ 2019-06-10 10:04  lpomeloz  阅读(131)  评论(0编辑  收藏  举报