leetcode 119. Pascal's Triangle II

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.


In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        start = ans = [1]
        for i in xrange(0, rowIndex):           
            ans = start + [1]
            for j in xrange(1, len(ans)-1):
                ans[j] = start[j]+start[j-1]
            start = ans
        return ans

还可以少一个临时变量,从后向前计算相加:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        ans = [1]
        for i in xrange(0, rowIndex):           
            ans = ans + [1]
            for j in xrange(len(ans)-2, 0, -1):
                ans[j] = ans[j]+ans[j-1]           
        return ans

 

也有使用dummy变量的做法:

1
2
3
4
5
6
7
8
9
10
class Solution(object):
    def getRow(self, rowIndex):
        """
        :type rowIndex: int
        :rtype: List[int]
        """
        row = [1]
        for _ in range(rowIndex):
            row = [x + y for x, y in zip([0]+row, row+[0])]
        return row

 另外就是数学解法,没有懂,TODO:

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
    vector<int> getRow(int k) {
        vector<int> ans(k+1,1);
        for(int i=1;i<=k/2;++i){         
           ans[k-i]= ans[i]=long(ans[i-1])*(k-i+1)/i;          
        }       
        return ans;
    }
};

 

posted @   bonelee  阅读(188)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-06-13 搜索引擎——用户搜索意图的理解及其难点解析,本质是利用机器学习用户的意图分类
2017-06-13 深入浅出时序数据库之预处理篇——批处理和流处理,用户可定制,但目前流行influxdb没有做
2017-06-13 FreeWheel基于Go的实践经验漫谈——GC是大坑(关键业务场景不用),web框架尚未统一,和c++性能相比难说
2017-06-13 CockroachDB——类似spanner的开源版,底层使用rocksdb存储,mvcc,支持事务,raft一致性,licence是CockroachDB Community License Agreement
2017-06-13 在Twitter信息流中大规模应用深度学习——推文的相关度计算使用了深度学习
点击右上角即可分享
微信分享提示