Pascal's Triangle

注意观察上一行跟当前行的规律即可,严格来说其实算是个动态规划题了

class Solution(object):
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        result = [[1]]

        for i in xrange(2, numRows + 1):
            tmp = [1]
            for j in xrange(len(result[-1]) - 1):
                tmp.append(result[-1][j] + result[-1][j + 1])
            tmp.append(1)
            result.append(tmp)

        return result[: numRows]

Pascal's Triangle II

这里只需要一行,那其实就是把动态规划里的滚动数组拿出来就行

class Solution(object):
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        result = [1]

        for i in xrange(1, rowIndex + 1):
            for j in xrange(len(result) - 1):
                result[j] += result[j + 1]
            result = [1] + result
        return result

results matching ""

    No results matching ""