119. Pascal's Triangle II

这一题是上一题的一个拓展,其实就是打印一行,但是这个一行在三角形中的行数要加1,所以循环其实多了一次,代码如下:

class Solution(object):
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        if rowIndex == 0:
            return [1]
        if rowIndex == 1:
            return [1,1]
        res = [[1,1]]
        for i in range(3,rowIndex+2):
            temp = [0 for j in range(i)]
            temp[0] = 1
            for k in range(1,i/2+1):
                temp[k] = res[-1][k -1] + res[-1][k]
            for k in range(i/2+1,i):
                temp[k] = temp[i-1-k]
            res.append(temp)
        return res[-1]

另一种省空间的做法,基于一种从后遍历的思想,从网上借鉴的,也是剑指offer里面提到过多次的思想:代码是我自己写的,这道题总的来说还是比较简单,代码如下:

class Solution(object):
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        if rowIndex == 0:
            return [1]
        if rowIndex == 1:
            return [1,1]
        temp = [0 for i in range(rowIndex+1)]
        temp[0] = 1
        temp[1] = 1
        for i in range(3,rowIndex+2):
            temp[rowIndex] = 1
            for j in range(rowIndex - 1, 0, -1):
                temp[j] = temp[j] + temp[j-1]
            temp[0] = 1
        return temp

你可能感兴趣的:(119. Pascal's Triangle II)