码迷,mamicode.com
首页 > 其他好文 > 详细

119. Pascal's Triangle II

时间:2016-06-24 10:49:01      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

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

链接: http://leetcode.com/problems/pascals-triangle-ii/

一刷,题目简单,但是需要看清题目,这次是从0行开始的,一开始每行最末尾填0的话可以把从 len(result) - 1到1的下标都一起包括,否则如果填1还要把最后一个去掉

class Solution(object):
    def getRow(self, rowIndex):
        if rowIndex < 0:
            return []
        result = [1]
        for row in range(rowIndex):
            result.append(0)
            for idx in range(len(result) - 1, 0, -1):
                result[idx] = result[idx] + result[idx - 1]
        return result
看到别人的解法,看懂了,但是关于两个range的下限为什么这么取没有想通。是一开始就想到的,还是refactor或是测试时候试出来的。
试着按照作者思路想,每一轮n要改动的范围是[1, n - 2],所以rowIndex = 0, 1没有合适的改动下标,所以row的下限是2, 而且输入n, 输出其实是第n+1行,所以上限是rowIndex + 1
内循环范围还没有想好。 
1 class Solution(object):
2     def getRow(self, rowIndex):
3         result=[1]*(rowIndex+1)
4         for row in range(2, rowIndex+1):
5             for idx in range(1, row):
6                 result[row - idx] += result[row - idx - 1]
7         return result

 

119. Pascal's Triangle II

标签:

原文地址:http://www.cnblogs.com/panini/p/5613107.html

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