码迷,mamicode.com
首页 > 编程语言 > 详细

Pascal's triangle II Leetcode Python

时间:2015-01-19 09:17:31      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:leetcode   python   array   

Given an index k, return the kth row of the Pascal‘s triangle.


For example, given k = 3,
Return [1,3,3,1].


Note:

Could you optimize your algorithm to use only O(k) extra space?

这题和前面一题的区别在于不用返回所有解,只需要返回index对应行就行。做法和前面的一样定义一个currow 和prerow


class Solution:
    # @return a list of integers
    def getRow(self, rowIndex):
        rownum=rowIndex+1
        currow=[1]
        if rownum==1:
            return currow
        if rownum>0:
            currow=[1]
            for index in range(rownum):
                prerow=currow
                currow=[1]
                for j in range(index-1):
                    currow.append(prerow[j]+prerow[j+1])
                currow.append(1)
        return currow


Pascal's triangle II Leetcode Python

标签:leetcode   python   array   

原文地址:http://blog.csdn.net/hyperbolechi/article/details/42855699

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!