leetcode118:杨辉三角

思想:先通过一个列表表达式生成一个全1的杨辉三角列表。然后开始循环,设置两个循环变量i和j,i控制第几行操作,j控制第几列操作。从杨辉三角图示可知,第一行和第二行不需改变,而且第三行,第四行,第五行只需要改1列,2列,3列,所以i的范围为0—nnumRows+1,j的范围为0—i-1。

class Solution:
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        ans = [[1] * n for n in range(1, numRows + 1)]
        for i in range(1, numRows + 1):
            for j in range(0, i - 2):
                ans[i - 1][1 + j] = ans[i - 2][j] + ans[i - 2][j + 1]
        return ans

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/83339207