力扣118:杨辉三角,c&&python

杨辉三角:

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
力扣118:杨辉三角,c&&python_第1张图片
这道题目在力扣中属于简单题目。直接解答。

int* getRow(int rowIndex, int* returnSize){
    static int a[34][34];//全局变量二维数组
    *returnSize = rowIndex + 1;
    int i, j;
    for (i = 0; i <= rowIndex; i++)
        a[i][0] = 1;
    for (i = 1; i <= rowIndex; i++)
        a[i][i] = 1;
    for (i = 2; i <= rowIndex; i++)
        for (j = 1; j < rowIndex; j++)
            a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
    return a[rowIndex];
}
  • 题目要求只是返回一行数据而已,因此我们直接返回一个一维指针,用两个循环为数组赋初始值,这个方法属于比较基本的思想实现,也比较容易看懂,不多讲。
class Solution(object):
    def getRow(self, rowIndex):
        n, b = 0, [1]
        while n < rowIndex:
            b = [1] + [b[i] + b[i + 1] for i in range(len(b) - 1)] + [1]
            n += 1
        return b
  • python也极易实现,用简单的迭代就可以实现。不需多讲。

你可能感兴趣的:(算法,leetcode,算法,python)