【LeetCode-119】 Pascal's Triangle II(C++)

题目要求:返回杨辉三角的第k行。

解题方法:

1.第一种方法就是根据杨辉三角的构成方式,每一行的元素等于上一行元素的左右两个数之和,然后将每一行都算出来循环计算。

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

2.利用杨辉三角的公式:result[i]=result[i-1]*(rowIndex-i+1)/i

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        vector<int> result(rowIndex+1,0);
        result[0]=result[rowIndex]=1;
        for(int i=1;i<=rowIndex/2;i++){
            result[i]=result[rowIndex-i]=(unsigned long)result[i-1]*(rowIndex-i+1)/i;
        }
        return result;
    }
};





版权声明:本文为liujiayu1015原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。